解决input type=file 同一个文件二次上传无效的问题

在做上传文件的时候,大家会引入input标签。但在实现的过程中,在上传一个文件后,第二次上传同一个文件时会无法触发上传的代码,问题其实这样解决。 

<input type="file" ref="referenceUpload" @change="onUpload" style=" 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