在文件上传时候,经常要手动删除input[type=file]上传的值,或者文件上传超过限制大小的时候重新上传的时候不能上传的问题
在谷歌、火狐上,我们我们直接设置value为空即可,但是ie10以下浏览器上不能解决。
html:
<input type='file' id="uploadInput" class="upfile" @change="fileChange">
js:
fileChange (evt) {
if (!evt.target) {
return
}
let target = evt.target
let isIE = false
if (window.addEventListener) {
isIE = false
} else if (window.attachEvent) {
isIE = true
}
let fileSize = 0
if (isIE && !target.files) {
let filePath = target.value
let fileSystem = new ActiveXObject('Scripting.FileSystemObject')
let file = fileSystem.GetFile (filePath)
fileSize = file.Size
} else {
fileSize = target.files[0].size
}
// let size = fileSize / 1024 // (10*1024*1024)
if (fileSize > 10 * 1024 * 1024) {
this.$Modal.warning({
title: '提示框',
content: '上传文件最大为10M,请重新上传。',
closable: true
})
let isIE10 = false
if (window.navigator.userAgent.indexOf('MSIE') >= 1) { // 判断ie10以及以下
isIE10 = true
} else {
isIE10 = false
}
let uploadInput = document.getElementById('uploadInput')
if (isIE10) {
// 关键部分ie10以下
let form = document.createElement('form')
let beforInput = uploadInput.nextSibling
let parentInput = uploadInput.parentNode
form.appendChild(uploadInput)
form.reset()
parentInput.insertBefore(uploadInput, beforInput)
} else { // 谷歌、火狐和ie11、edge
target.value = ''
}
// 关键部分
return
}
let name = target.value
let fileName = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
if (fileName !== 'jpeg' && fileName !== 'png' && fileName !== 'jpg') {
this.$Modal.warning({
title: '提示框',
content: '请上传JPG、JPEG、PNG格式的文件',
closable: true
})
target.value = ''
return
}
},
解决方式:创建一个表单元素,把input放进去,重置表单,再把input取出来你放到原来的地方。
总结代码:
function resetInputValue(){
let isIE10 = false
let uploadInput = document.getElementById('uploadInput')
if (window.navigator.userAgent.indexOf('MSIE') >= 1) { // 判断ie10以及以下
isIE10 = true
} else {
isIE10 = false
}
if (isIE10) {
let form = document.createElement('form')
let beforInput = uploadInput.nextSibling
let parentInput = uploadInput.parentNode
form.appendChild(uploadInput)
form.reset()
parentInput.insertBefore(uploadInput, beforInput)
} else {
uploadInput.value = ''"
}
}
网友评论