使用场景,使用el-upload上传文件,选择文件后不立即上传到服务器上,点击提交按钮时与其他form表单数据一起提交,类似的需求,相信有很多小伙伴遇到,可能也会遇到跟我一起的问题,在这里记录一下
<el-upload
class="upload-file"
action=""
:on-change="handleChange">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
问题1:el-upload文件上传组件,设置auto-upload为false,on-change事件只触发一次
由于原生的input type="file"不管文件上传成功与否,已添加的文件已经被记录了,所以上传文件时,不会触发change事件,这里我们就把已经添加的文件记录清除来解决该问题
html(给el-upload添加ref属性)
<el-upload
class="upload-file"
ref="upload"
action=""
:on-change="handleChange">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
javascript(使用一个变量保存已上传的文件)
handleChange(file) {
this.file = file;
this.$refs.upload.clearFiles(); // 清空文件
}
问题2:file与form表单数据一起提交
/** 保存 */
saveUpload() {
if (!this.file) return this.$message.warning('请选择文件')
this.param = new FormData()
// 文件
this.param.append('file', this.file.raw, this.file.name)
// ID
this.param.append('id', this.id)
const token = JSON.parse(localStorage.getItem("token")) || ''
// 设置请求头
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': token
}
};
axios.post(this.uploadUrl, this.param, config).then(
response => { console.log('res', response) },
err => { reject(err); }
).catch((error) => { reject(error) })
}
至此,问题总结记录完毕