如图:
<input type="file" hidden accept="image/*" ref="fileBtn" @change="handleUpload"
style="display: none;" :key="fileKey" />
<div v-if="!userAvatar && !previewImage" class="imgs" @click="updateAvatar"
style="position: absolute;top: 20px;left: 97px;">
<el-icon style="margin-bottom: 10px;font-size: 50px;color:rgba(39, 120, 255, 0.9);"
class="el-icon--upload"><upload-filled /></el-icon>
<div>上传图片,请<span style="color:rgba(39, 120, 255, 0.9);cursor: pointer;">点击上传
</span></div>
<div>注:仅支持gif/jpg/jpge/</div>
<div>png文件,文件大小不超多3M</div>
</div>
//回显上传图片的
<img v-else-if="previewImage" class="userimg" @click="updateAvatar" style="position: absolute;top: 20px;left: 97px;width: 151px;height: 201px;" :src="previewImage">
const fileBtn = ref()
const updateAvatar = (message, callback) => {
ElMessageBox.confirm(
'请上传自己真实照片!',
'提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(() => {
// console.log('点击确定');
fileBtn.value.click()
})
.catch(() => {
ElMessage({
type: 'info',
message: '取消',
})
})
}
const formdatas = ref()
const previewImage = ref()
// 上传头像
const handleUpload = async (e) => {
const files = Array.prototype.slice.call(e.target.files)
console.log(files, "files")
if (!files) {
return
}
const file = event.target.files[0];
if (file) {
previewImage.value = ''
// 使用URL.createObjectURL生成预览URL
previewImage.value = URL.createObjectURL(file);
// 这里可以添加其他逻辑,比如发送到后端
}
const formdata = new FormData()
formdata.append('file', files[0])
formdatas.value = formdata
}
//最后调用上传图片接口,把formdatas.value传给后端就可以了
这里上传完成,清空回显图片,可以让用户再次上传
const fileKey = ref(0)
const clearInput = () => {
//这是需求里面的条件渲染,可忽略
userAvatar.value = ''
previewImage.value = ''
fileKey.value++
}
加了 const fileKey = ref(0)我发现如果上传一张a图片,清空previewImage.value = '',当我再次上传a图片有问题。
当您遇到使用 <input type="file">
标签上传文件时,如果前后两次上传同一个文件,但浏览器没有触发 change
事件,这通常是因为浏览器对文件选择进行了优化。浏览器可能认为既然用户选择了相同的文件,就没有必要重新触发 change
事件,因为从用户的角度来看,没有发生任何变化!
所以更改 key 以强制重新渲染 input!