Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios: Upload progress for multiple file uploads

Following https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html I've set up a file upload with progress bar.

However, I have <input type="file" multiple>, so the upload is inside a loop like this:

for (var i=0; i<files.length; i++)
{
    var config = {
        onUploadProgress: function(progressEvent) {
            var what = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
        }
    };
    axios.post(url, data, config)
        .then(function (response) {
    });                            
}

The question is: How can I assign the upload progress (see var what) to the corresponding file?

Everything I've tried didn't work:

  • The callback function onUploadProgress apparently doesn't take any second argument: https://github.com/mzabriskie/axios#request-config

  • The injected progressEvent object doesn't contain any information about the uploaded file. Example:

    progress { target: XMLHttpRequestUpload, isTrusted: true, lengthComputable: true, loaded: 181914, total: 181914, currentTarget: XMLHttpRequestUpload, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false }
    
  • The looping variable i is accessible in principle - however, it's always at the last position (since the loop has finished when onUploadProgress gets called during the upload)

  • I couldn't figure out a way to access axios' data from inside onUploadProgress

  • this refers to:

    XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, ontimeout: null, onloadend: null }
    

Any other ideas?

like image 646
Thomas Landauer Avatar asked Dec 23 '22 16:12

Thomas Landauer


1 Answers

You can create a function that return another decorated function with some Id as parameter.

Example:

const myUploadProgress = (myFileId) => (progress) => {
  let percentage = Math.floor((progress.loaded * 100) / progress.total)
  console.log(myFileId)
  console.log(percentage)
}

for (var i=0; i<files.length; i++) {
  var config = {
    onUploadProgress: myUploadProgress(files[i].id)
  };

  axios.post(url, data, config).then(function (response) {});                            
}

If you don't have ES6 you can do:

function myUploadProgress(myFileId) {
  return function(progress) {
    ...
  }
}

(I'm using a similar code on my project and it works like a charm)

like image 74
Ricardo Silva Avatar answered Dec 28 '22 12:12

Ricardo Silva