vue element el-upload上传文件遇到的问题汇总
两个文件作为FormData的主参数,其他录入的字段需要扔到一个对象中 作为FormData的额外参数
·
这几天真的要被el-upload搞疯掉了,无数的坑!
首先 这个需求是这样的 一个form表单 里面 有两个上传文件的地方(此处的文件不立即进行上传) 还有其他需要录入的字段 点击保存 一起传入后台。
两个文件作为FormData的主参数,其他录入的字段需要扔到一个对象中 作为FormData的额外参数
后端接口接收的是 多个files文件和额外附带的参数对象(字符串类型)
- 视图部分(这里只有上传组件 还有其他表单组件哦!)
<el-upload
ref="upload"
:limit="1"
multiple
drag
action=""
:file-list="fileList"
:on-change="beforeAvatarUpload"
:on-remove="handleRemove"
:on-exceed="handleExceed"
:auto-upload="false"
accept=".zip,.rar">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div slot="tip" class="el-upload__tip">上传培训资料,且只能上传.zip/.rar文件</div>
</el-upload>
- 上传相关回调函数
// 上传文件超出个数
handleExceed() {
this.$message.warning(`当前只能选择上传1个文件!`);
},
// 移除文件
handleRemove(res, file, fileList) {
this.$message.warning(`移除当前${res.name}资料,请重新选择资料上传!`);
this.fileList = fileList;
},
// 文件改变时
beforeAvatarUpload (file) {
debugger
const isJPG = /\.(zip|rar)$/.test(file.name)
const isLt2M = file.size / 1024 / 1024 < 20
if (!isJPG) {
this.$message.error('仅支持上传.zip、.rar为后缀的文件!')
return false
}
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 20MB!')
return false
}
let flag = false
this.fileList.forEach(e => {
if (e.name === file.name) flag = true
})
if (flag) {
return false
}
this.filename1 = file.name
this.fileList.push(file)
console.log(this.fileList);
},
- 保存组参FormData
let formData =new FormData()
this.fileList.forEach(e=>{
formData.append('files',e.raw) //如果用上传文件的on-change函数拿files的话 需要找到对应e的raw,不能直接给e,否则前端传入的后端的是[object,object]
})
formData.append('req',JSON.stringify(data).toString()) //附带的额外参数 后台需要转成String字符串
const loading = this.openFullScreen()
TrainingMessage(formData).then((res) =>{
debugger
const data = res;
if(data.resHeadDto.errCode === '000000'){
this.$notify({
title: '成功',
message: data.resHeadDto.errMsg,
type: 'success'
});
更多推荐
已为社区贡献3条内容
所有评论(0)