前端:templete中
<input type="file" value="" id="file" @change="uploadTest">
script中
methods: {
uploadTest (e) {
let formData = new FormData()
let data = JSON.stringify({
aa: 'xxx',
bb: 123
})
formData.append('file', e.target.files[0])
formData.append('data', new Blob([data], {type: 'application/json'})) // 同时上传文件和JSON,这里1.用动new Blob;2[data]中括号;3.必须加type,postman见本站https://blog.csdn.net/FRESHET/article/details/121286971
// 后台测试地址
let url = 'http://192.168.1.103:8081/upload'
let config = {
headers: {'Content-Type': 'multipart/form-data'}
}
this.$axios.post(url, formData, config).then(function (response) {
console.log(response.data)
})
}
}
后台代码:
@CrossOrigin
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestPart("file") MultipartFile file,@RequestPart Map<String,Object> data ) {
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName = file.getOriginalFilename();
String filePath = "E:\\vuetest\\vue_upload\\";
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
System.out.println(data.get("aa"));
System.out.println(data.get("bb"));
System.out.println("upload ok");
return "上传成功";
} catch (IOException e) {
System.err.println(e.toString());
}
return "上传失败!";
}
效果:
xxx
123
upload ok