首页 > 解决方案 > 有什么方法可以将变量分配给 axios 请求并在 onUploadProgress 中访问它

问题描述

我在 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++;
        }

标签: arraysvue.jsvuejs2axioses6-promise

解决方案


而不是使用箭头函数onUploadProgress- 您可以使用bind()向函数添加额外的第一个参数,该参数将是对相应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);    
}

推荐阅读