vue项目中使用axios上传文件显示进度

 

上传文件:

            

                {{filename}}

                +请选择文件上传+

                @change="upload" multiple="multiple" />

            

           

 

           

上传进度:

            

                

                {{(uploadRate*100).toFixed(2)}}%

            

   data() {

            return {

              uploadRate: 0,

               filename: '',

               uploadStyle: {

                   width: '0%'

               }

     }

}

 

 

methods: {

             upload: function (e) {

                  var vm = this;

                   var formData = new FormData();

                   formData.append("name", "Alax");

                   for (var i = 0; i < e.target.files.length; i++) {

                       var file = e.target.files[i];   //取第1个文件

                       formData.append("file", file);

                       vm.filename = file.name;

                       console.log(file);

                   }

 

                   var config = {

                       headers: { 'Content-Type': 'multipart/form-data' },

                       onUploadProgress: function (e) {//上传过程中一直触发这个函数计算上传的进度

                           console.log(e)

                           //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量

                           //如果lengthComputable为false,就获取不到e.total和e.loaded

                           if (e.lengthComputable) {

                               var rate = vm.uploadRate = e.loaded / e.total;  //已上传的比例totalz是总的上传的内容大写。loaded是现在上传的内容的大学

                               if (rate < 1) {

                                   //这里的进度只能表明文件已经上传到后台,但是后台有没有处理完还不知道

                                   //因此不能直接显示为100%,不然用户会误以为已经上传完毕,关掉浏览器的话就可能导致上传失败

                                   //等响应回来时,再将进度设为100%

                                   vm.uploadRate = rate;

                                   vm.uploadStyle.width = (rate *100).toFixed(2)+ '%';

                               }

                           }

                       }

                   };

                   axios.post("/resource/microvideoupload", formData, config)

                       .then(function (data) {

                           console.log(data);

                           var json = data.data;   //后台实际返回的结果

                           if (json.result) {

                               vm.uploadRate = 1;

                               vm.uploadStyle.width = '100.00%';//onuploadprogress 事件中显示上传为100%并不准确,一定要等到响应回来才能认为完成了100%,不然用户此时关闭了浏览器的话,上传就失败了。或者有其它逻辑时,此时点提交,就会导致后台找不到上传的文件路径等问题。

                           } else {

                               alert(json.msg);

                           }

                       })

                       .catch(function (err) {

                           console.log(err);

                       });  

             },

}

 

             

你可能感兴趣的:(vue)