需求:在一个表单中既要提交数据,又到提交图片,并且图片提交的url( /**
/**
/pic?id=*)中某个参数(id)是提交数据后返回的。
HTML
<el-upload
class="upload-demo"
name="file" //对应后端接收参数名
ref="upload"
drag
:action="newUrl" //设置绑定url
:limit="1"
:auto-upload="false" //关闭自动提交
:headers="headers"
:on-success="uploadAttachmentSuccess"
:on-error="uploadAttachmentfail"
:before-upload="beforeUploadHandle" //提交前操作
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">
只能上传jpg/png文件,且不超过500kb
</div>
</el-upload>
<el-button type="primary" @click="handleAdd()">确 定</el-button>
JS
addObj将用于提交表单数据到后端,后端返回该条数据在数据库的id
this.newId = response.data.data//获取后端返回的参数
this.$refs.upload.submit()//手动提交
handleAdd() {
addObj({
casnum: this.addContent.casnum,
formulaPlain: this.addContent.formulaPlain,
nameEn: this.addContent.nameEn,
nameCn: this.addContent.nameCn,
refText: this.addContent.ref_text,
refLink: this.addContent.ref_link,
refTitle: this.addContent.ref_title,
})
.then((response) => {
//新增分子式后返回其id
this.newId = response.data.data;
this.addDetails = false;
this.$message.success("添加成功");
this.getList();
this.addContent = {};
this.$refs.upload.submit();
})
.catch(() => {
this.$message.error("添加失败");
this.addContent = {};
this.addDetails = false;
});
},
上传前设置
这里设置对 :action=“newUrl” 进行参数绑定
beforeUploadHandle(file) {
return new Promise((resolve)=>{
this.$nextTick(()=>{
this.newUrl = "/**/**/pic?id=" + this.newId;
resolve();
})
})
},
后端接口代码
最后实际请求 /**
/**
/pic?id=22**//例如后端返回参数22
@PostMapping("/pic")
public R updatePic(@RequestParam("file") MultipartFile file, @RequestParam("id") int id){
return (vocMolucularService.updatePic(file,id));
}