文件上传和字段一开始困惑了自己很久,后来发现有一种方法formdata可以将文件和表单一起传到后端,首先使用el-upload组件获取到本地上传的文件,我需要手动上传因此设置:auto-upload=false
,
知识点:给组件上添加一个ref="upload"就可以获取该组件对象,如果不是组件就是获取该元素,组件通信的一种方式
//手动上传
submitUpload() {
this.$refs.upload.submit();
},
//action是上传的服务器地址,设置为空,因为需要和其它字段统一进行发送请求
:http-request="uploadFile"
async uploadFile(fileobj) {
this.menuId = this.$route.params.id;
// 获取图片路径
console.log(fileobj);
let formData = new FormData();
formData.append("file", fileobj.file);
formData.append("menuId", this.menuId);
formData.append("attName", this.attName);
formData.append("fileType", this.fileName.name);
formData.append("status", this.fileTimeType);
// fileTimeType
let config = {
headers: { "Content-Type": "multipart/form-data" },
};
const res = await this.$http.post(
"/attachment/upload/file",
formData,
config
);
if (res.data.code === 0) {
this.$message.success("文件上传成功");
this.getResourceList();
this.$refs.upload.clearFiles();
} else {
this.$message.err("文件上传失败");
}
},
补充:后端需要的是formdata形式