Axios: Upload progress for multiple file uploads

好久不见. 提交于 2019-12-03 17:24:52

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)

This is a variable scoping issue. In JavaScript var declares a variable in a function scope. There are a lot of potential solution, depending on which version of ES your target browser supports. I'll use the same function to demonstrate:

setTimeout(function(){ console.log(i); }, i * 100);

Using var this will print out '5' 5 times. We want it to print out 0 1 2 3 4.

If you have Array#forEach, you can use that since the closure creates a new function scope

[0, 1, 2, 3, 4].forEach(function(i) { 
    setTimeout(function(){ console.log(i); }, i * 100);
});

If you have access to let, let and const uses block scoping instead (ie. the variable is scoped to the nearest set of { ... }).

for (let i = 0; i < 5; i++) {
    setTimeout(function(){ console.log(i); }), i * 100);
}

If you don't have access to either of those, you can use an IIFE. It's really ugly but it gets the job done.

for (var i = 0; i < 5; i++){ 
    (function() {
        var newI = i;
        setTimeout(function(){ console.log(newI); }, i * 100); 
    })();
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!