网上查阅了很多资料,结果都不尽人意,废话不多说,直接上代码。
前端代码:
<el-upload
:on-preview="previewFile"
limit="1"
:on-change="changeFile"
:auto-upload="false"
:data="uploadForm.data">
<template #trigger>
<el-button size="small" type="primary">选取附件</el-button>
</template>
<el-button style="margin-left: 10px;" size="small" type="success"
@click="submitUpload">上传到服务器</el-button>
</el-upload>
其中:
1.on-preview: 点击文件列表中已上传的文件时的钩子(一般用作文件预览,在这里不重要)
2.on-change: 文件状态改变时的回调函数,可以用来给file赋值
const file = ref()
const changeFile = (uploadFile: UploadFile) => {
file.value = uploadFile;
}
3. :auto-upload="false" 这一步比较重要,必须要把自动上传关闭,因为我们会自己写方法上传。
4. :data="uploadForm.data" 需要携带的参数
const uploadForm = reactive({
data: {
fileId: '',
name: '',
type: ''
}
})
5. 重要的 submitLicenseUpload 方法来了:
const submitUpload = () => {
const jsonStr = JSON.stringify(uploadForm.data);
const blob = new Blob([jsonStr], {
type: 'application/json'
});
let formData = new FormData();
formData.append("obj", blob);
// 这里很重要 file.value.raw才是真实的file文件,file.value只是一个Proxy代理对象
formData.append("file", file.value.raw);
let url = '你的后端url'
let method = 'post'
let headers =
{
'Accept': 'application/json',
'Content-Type': 'application/json'
};
axios({
method,
url,
data: formData,
headers
}).then(res => {
console.log(res);
console.log(res.data);
});
}
后端代码(springboot controller):
@PostMapping("upload")
@Operation(summary = "上传")
@ResponseBody
//注意 带参数的话,这里需要用RequestPart,RequestParam进不来
public Result<YourClass> upload(@RequestPart("file") MultipartFile file, @RequestPart("obj") AttachmentVO vo) throws Exception {
return null;
}
至此,结束!