Apr 17, 2020
0
Level 1
Show progress bar only if file upload starts
I'm using jQuery and Ajax to upload files and I also have a progress bar to display the progress of the upload. I want this progress bar to appear only if the upload progress starts not when I get validation errors from the controller. How can I do it?
Here is my code :
$('[type="file"]').change(function () {
var formData = new FormData();
formData.append('video', $(this)[0].files[0]);
$.ajax({
url: '/url',
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: formData,
headers: {
'X-CSRF-TOKEN': $('[name="csrf-token"]').attr('content')
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('loadstart', function () {
$('#progressbar').fadeIn(100);
});
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var percentageComplete = (e.loaded / e.total) * 100;
$('#progressbar span').css('width', percentageComplete + '%');
}
});
return xhr;
},
success: function (response) {
if (response.status == 'error') {
$(this).parent().append('<p class="text-danger" role="alert">' + response.message + '</p>');
} else {
//
}
}
});
});
Please or to participate in this conversation.