有没有办法将变量分配给 axios 请求并在上传进度中访问它



我在 Vue 中使用以下代码。在这里,我使用多个 axios 请求同时上传多个文件。在此代码中一切正常。 但是我想要一种方法来查看文件上传了多少%。看到有数组this.upload具有进度属性的文件对象。所以我想为特定对象更新此属性。所以我可以向用户显示文件上传进度

for(var file of event.target.files){
if(!this.isValidFormat(file)) continue;
var thumb = await this.getThumb(file);
this.upload.push({
name: file.name,
index: parseInt(Math.round(file.size / (1024))),
size: (file.size / (1024 * 1024)).toFixed(2) + ' MB',
progress: 0,
thumbnail: thumb,
path: null
});
const formData = new FormData();
formData.append('image', file, file.name);
formData.append('path', 'tmp');
formData.append('index', increment);
axios.post('web/upload', formData, {
onUploadProgress: progressEvent => {
//console.log(this.config);
const index = parseInt(Math.round(progressEvent.total / 1024));
//console.log(index)
var u = this.upload.find(u => u.index == index);
if(u !== undefined){
u.progress = Math.floor((progressEvent.loaded * 100) / progressEvent.total);    
}
}
}).then(res => {
this.upload[res.index].path = res.path;
console.log(this.upload)
});
increment++;
}

您可以使用bind()向函数添加额外的第一个参数,而不是使用箭头函数进行onUploadProgress,该参数将引用相应的file对象:

for(var file of event.target.files){
if(!this.isValidFormat(file)) continue;
var thumb = await this.getThumb(file);
const fileObject = {
name: file.name,
size: (file.size / (1024 * 1024)).toFixed(2) + ' MB',
progress: 0,
thumbnail: thumb,
path: null
};
this.upload.push(fileObject);
const formData = new FormData();
formData.append('image', file, file.name);
formData.append('path', 'tmp');
formData.append('index', increment);
axios.post('web/upload', formData, {
onUploadProgress: this.calcProgress.bind(this, fileObject)
}).then(res => {
this.upload[res.index].path = res.path;
console.log(this.upload)
});
increment++;
}
function calcProgress(fileObj, progressEvent)
{
fileObj.progress = Math.floor((progressEvent.loaded * 100) / progressEvent.total);    
}

你可以用 vuex 提交值,并在你想要的地方用 getter 使用它。

https://vuex.vuejs.org/guide/mutations.html

https://vuex.vuejs.org/guide/getters.html

最新更新