在项目中需要使用文件上传,和表单内容同时提交的情况
1.使用element中Upload 上传组件,除了上传文件还需要同时提交其他数据,可以进行手动上传
但是upload组件中上传的地址action必选参数,不能删除,此时将action="#"即可。
:auto-upload="false"即设置为手动上传
<el-form-item label="文件上传:" prop="uploadFile">
<el-upload
class="upload-demo"
action="#"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-change="uploadChange"
multiple
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList"
:auto-upload="false"
>
<el-button size="small" type="primary">点击上传</el-button>
<span slot="tip" class="el-upload__tip">
只能上传1个文件
</span>
</el-upload>
</el-form-item>
2.手动上传时候,文件取值为filelist列表中每一项的raw,用formdata上传文件,file:(binary)
uploadChange(file, fileList) {
this.form.file = fileList[0].raw;
}
3.表单提交
onSubmit(formName) {
let formData = new FormData();
formData.append("file", this.form.file);
formData.append("username", this.form.username);
formData.append("appid", this.form.appid);
formData.append("appName", this.form.appName);
formData.append("groupId", this.form.groupId);
formData.append("uploadPipe", this.form.uploadPipe);
formData.append("fileUrl", this.form.fileUrl);
formData.append("groupName", this.form.groupName);
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
this.$refs[formName].validate(valid => {
if (valid) {
this.$axios
.post(this.$apiUrl.fileUpload, formData, config)
.then(res => {
if (res.status == "200") {
this.$message({
message: "提交成功",
type: "success"
});
this.$router.push("/");
}
});
} else {
return false;
}
});
},
作者:前端林木木
链接:https://www.jianshu.com/p/5025c48ba2f4