前端使用的upload:
<el-upload
action=""
:http-request="uploadPost"
:show-file-list="false"
:on-change="onChange"
list-type="picture">
<img :src="dialogImageUrl" >
</el-upload>
onChange(file,fileList){
this.dialogImageUrl = file.url;
this.file = file;
console.log(file);
},
uploadPost(){
let formData = new FormData();
formData.append('file',this.file.raw);
// 文件上传必须设置http请求头信息
request.post("/api/main/uploadPicture",formData,{
headers:{'Content-Type':'multipart/form-data;charset=utf-8'}
}).then(res => {
if(res.code == '0'){
this.$message.success("上传成功!");
}else{
this.$message.error(res.code+' 上传失败!'+res.msg);
}
},error => {
console.log('253: 错误! '+error);
})
},
这里最重要的是formData.append('file',this.file.raw);取得是this.file.raw
然后记得设置http请求头{
headers:{'Content-Type':'multipart/form-data;charset=utf-8'}
}
后端:
@PostMapping("/uploadPicture")
public Result<?> uploadPicture(@RequestBody MultipartFile file){
try{
if(!file.isEmpty()){
System.out.println("上传头像");
String imgPath = "C:/Users/Administrator/Desktop/img";
File f = new File(imgPath+new Date().getTime()+file.getOriginalFilename());
byte[] arr = file.getBytes();
file.transferTo(f);
return Result.success();
}else{
return Result.error("139","图片为空");
}
}catch (Exception e){
e.printStackTrace();
return Result.error("139",e.getMessage());
}
}
这里使用@RequestBody MultipartFile file,也可以使用@RequestParam("file") MultipartFile file,只要对应前端的参数名就行,formData.append('file',this.file.raw)