解決input type=file 同一個文件二次上傳無效的問題


在做上傳文件的時候,大家會引入input標簽。但在實現的過程中,在上傳一個文件后,第二次上傳同一個文件時會無法觸發上傳的代碼,問題其實這樣解決。 

<input type="file" ref="referenceUpload" @change="onUpload" style="width: 78px;outline: none;height: 30px;z-index: 999;opacity: 0;"></Input> <Button type="primary" style="margin: 0px 0px 0px -83px;">上傳文件</Button>

js:

//上傳PDF文件 onUpload(e) { var formData = new FormData(); formData.append('file', e.target.files[0]); formData.append('token', localStorage['token']); this.loadingst(); this.axios.post('/report/upload', formData, { emulatejsON: true }).then(function(res) { this.loadingsts(); if(res.data.code == 200) { this.file_path = res.data.data.save_path; this.fromValue.report_name = res.data.data.name; this.file_name = res.data.data.name + '.pdf'; this.file_size = res.data.data.size; this.file_size_name = ' | ' + res.data.data.size; this.$Notice.success({ title: '提示', desc: '上傳成功 !', duration: 3 }) } else { this.$Notice.warning({ title: res.data.msg, duration: 3 }); } }.bind(this)) e.target.value = ''; },

 

關鍵

實現功能的關鍵在於最后一句:  

e.target.value='';

因為觸發條件為change,當input里儲存的文件沒有變化的時候是不會進入函數的,所以在上傳的最后,把input中的value值清空就好了。  

廣州VI設計公司https://www.houdianzi.com

問題發生背景
使用input[type=file] 實現文件上傳功能,通過onchange事件觸發js代碼,這個時候第一次上傳是完全沒問題的,不過當你第二次上傳文件時,如果是不同於上一次上傳文件的話是可以正常上傳的,不過如果你選擇的還是上一個文件,也就是兩次上傳的文件重復了,那么就會上傳失敗。

 

原因
input是通過onchange事件來觸發js代碼的,由於兩次文件是重復的,所以這個時候onchange事件是沒有觸發到的。

 

解決方案
方案一: 刪除input標簽的代碼並重新添加dom節點,不過這個方案太笨拙,所以使用方案二。
方案二: 把input的value重新設置為空就好了,

document.getElementById('uploadFile').value = null; this.$refs.referenceUpload.value = null;//vue


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM