一,前言
最近在用Vue,然后上传文件时需要显示进度,于是网上搜了一下,经过自己实测终于也弄明白了
二,效果
![](https://i-blog.csdnimg.cn/blog_migrate/155477e05667ae6849fcbb5b7e27bd4b.png)
三,代码
HTML代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | < div id="app"> < h4 >上传文件:</ h4 > < p class="input-zone"> < span v-if="filename">{{filename}}</ span > < span v-else>+请选择文件上传+</ span > < input type="file" name="file" value="" placeholder="请选择文件" @change="upload" multiple="multiple" /> </ p > <p>上传进度:</p> <div class="progress-wrapper"> <div class="progress-progress" :style="uploadStyle"></div> <div class="progress-rate">{{(uploadRate*100).toFixed(2)}}%</div> </div> </ div > |
CSS代码
1 2 3 4 5 | .input-zone { width : 500px ; color : blue ; font-size : 14px ; position : relative ; } .input-zone input[type= 'file' ] { opacity: 0 ; width : 100% ; height : 100% ; position : absolute ; left : 0 ; top : 0 ; z-index : 2 ; } .progress-wrapper { position : relative ; height : 50px ; border-radius: 5px ; background-color : lightgrey; } .progress-wrapper .progress-progress { position : absolute ; left : 0 ; top : 0 ; height : 100% ; width : 0% ; border-radius: 5px ; background-color : darkturquoise; z-index : 1 ; } .progress-wrapper .progress-rate { position : relative ; text-align : center ; font-size : 14px ; line-height : 50px ; height : 100% ; z-index : 2 ;} |
JS代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | var app = new Vue({ el: "#app" , data: { 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( "进度:" ); console.log(e); //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量 //如果lengthComputable为false,就获取不到e.total和e.loaded if (e.lengthComputable) { var rate = vm.uploadRate = e.loaded / e.total; //已上传的比例 if (rate < 1) { //这里的进度只能表明文件已经上传到后台,但是后台有没有处理完还不知道 //因此不能直接显示为100%,不然用户会误以为已经上传完毕,关掉浏览器的话就可能导致上传失败 //等响应回来时,再将进度设为100% vm.uploadRate = rate; vm.uploadStyle.width = (rate *100).toFixed(2)+ '%' ; } } } }; axios.post( "/ajaxPage/VueUpload.aspx?method=upload" , formData, config) .then( function (data) { console.log(data); var json = data.data; //后台实际返回的结果 if (json.result) { vm.uploadRate = 1; vm.uploadStyle.width = '100.00%' ; } else { alert(json.msg); } }) . catch ( function (err) { console.log(err); }); } } }) |
四,总结
1.其实单文件上传和多文件上传的区别就是 input标签中多了一个属性
2.onuploadprogress 事件中显示上传为100%并不准确,一定要等到响应回来才能认为完成了100%,不然用户此时关闭了浏览器的话,上传就失败了。或者有其它逻辑时,此时点提交,就会导致后台找不到上传的文件路径等问题。