How to get progress of chunked file upload via ajax?
I have writen a jQuery acript that waits for file input change and then takes all the files for upload in chunks. I am using the FileReader API to slice the file apart. Now I get console log every time: a part of a file gets uploaded, the upload of last part is finished and the file processing on server starts and the when the processing finishes. What I need is to get the progress of the uploading in percentage for every file that is being uploaded (and make a console log of it, for example). That would be easy if there was just one file, but since I am slicing the file into pieces and send every piece via ajax, I can't get it done. Any suggestions? Here is the jQuery script:
$(document).on('change', '#files', function() { var input = this; for (var i = 0; i < input.files.length; i++) { initializeFileReader(input.files[i]); }});function initializeFileReader(inputFile) { var readFile = new FileReader(), file = inputFile; readFile.onload = function(e) { splitSend(new Uint8Array(e.target.result), file); }; readFile.readAsArrayBuffer(file);}function splitSend(dataArray, file) { var i = 0, formData, blob; var parts = 1; var chunkSize = 2*1000*1024; for (; i < dataArray.length; i += chunkSize ) { blob = new Blob([dataArray.subarray(i, i + chunkSize)]); formData = new FormData(); if (dataArray.length>=chunkSize) { formData.append('files', blob, file.name + '.part' + (i / (chunkSize))); } else { formData.append('files', file, file.name); } formData.append('directory', $('form#upload').attr('data-directory')); $.ajax({ url: 'upload.php', type: 'POST', data: formData, cache:false, processData: false, contentType: false, success: function() { console.log('Uploaded part '+parts+' of '+file.name); if (dataArray.length>=chunkSize) { if (parts == Math.ceil(file.size/chunkSize) ) { console.log('Processing '+file.name); $.ajax({ url:'upload.php', method: 'POST', data: 'processfile=true&filename='+file.name+'&directory='+$('form#upload').attr('data-directory')+'&parts='+parts, success: function(){ console.log('Finished uploading '+file.name); } }); } } else { console.log('Finished uploading '+file.name); } parts++; }, }); }}