Axios:多个文件上传的上传进度 [英] Axios: Upload progress for multiple file uploads
问题描述
跟随 https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html 我已经设置了带有进度条的文件上传.
Following https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html I've set up a file upload with progress bar.
但是,我有<input type="file" multiple>
,所以上载在这样的循环中:
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) {
});
}
问题是:如何将上传进度(请参见var what
)分配给对应的文件?
The question is: How can I assign the upload progress (see var what
) to the corresponding file?
我尝试过的所有方法都无效:
Everything I've tried didn't work:
-
回调函数
onUploadProgress
显然没有任何第二个参数: https ://github.com/mzabriskie/axios#request-config
The callback function
onUploadProgress
apparently doesn't take any second argument: https://github.com/mzabriskie/axios#request-config
注入的progressEvent
对象不包含有关上载文件的任何信息.示例:
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 }
原则上可以访问循环变量i
-但是,它始终位于 last 位置(因为在上载期间调用onUploadProgress
时循环已完成)
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)
我想不通从onUploadProgress
this
是指:
XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, ontimeout: null, onloadend: null }
还有其他想法吗?
推荐答案
您可以创建一个函数,该函数返回另一个带有一些Id作为参数的修饰函数.
You can create a function that return another decorated function with some Id as parameter.
示例:
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) {});
}
如果没有ES6,可以执行以下操作:
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)
这篇关于Axios:多个文件上传的上传进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!