ElementUI 上传文件和额外参数
需求是:
现有一后端接口,POST类型,参数为
@RequestParam("file") MultipartFile file,int courseId
前端需要传文件和额外的参数,后端没给任何指导,瞎琢磨了半天才搞出来。
利用elementUI封装好的el-upload组件进行上传操作,先上html代码:
<el-upload
:multiple="false"
:show-file-list="false"
:http-request="uploadExcel"
action="string"
>
<el-button size="small" type="primary">上传文件</el-button>
注意这里的
:http-request
这是elementUI封装好的,用来覆盖默认的上传行为,可以自定义上传的实现。我这里写了一个自己的函数uploadExcel,内容如下:
uploadExcel(param) {
let fd = new FormData();
fd.append('file', param.file); // 传文件
fd.append('courseId', this.mycourseId); // 传courseId
this.$axios.post('/CourseDetail/addStudentByExcel', fd).then((resp) => {
const { data } = resp;
console.log(data)
if (data.success === false) {
this.$message({
message: data.message,
type: 'warning'
});
} else {
this.$message({
message: data.message,
type: 'sucess'
});
}
});
},
注意,要取得此处上传的文件,必须使用param这个参数名,然后通过param.file拿到上传的文件。
这之后就很简单了,因为后端要的是MultipartFile,所以创建一个FormData对象,在里面放入文件和额外的参数,然后通过axio的post方法传给后端就可以了。
参考自:https://www.cnblogs.com/smile-fanyin/p/12495012.html
https://blog.csdn.net/m0_37835906/article/details/88915959