最近在用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