最近在用Vue,而后上传文件时须要显示进度,因而网上搜了一下,通过本身实测终于也弄明白了javascript
<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>
.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;}
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标签中多了一个属性 css
multiple="multiple"
2.onuploadprogress 事件中显示上传为100%并不许确,必定要等到响应回来才能认为完成了100%,否则用户此时关闭了浏览器的话,上传就失败了。或者有其它逻辑时,此时点提交,就会致使后台找不到上传的文件路径等问题。html