记一次使用上的错误:先上代码
@PostMapping("/upload")
public void upload(@RequestPart("file")MultipartFile file, @RequestParam("id") Long id) {
System.out.println("----------------------------------------文件上传成功");
}
@PostMapping("/upload")
public void upload(@RequestPart("file")MultipartFile file, @RequestPart("id") Long id) {
System.out.println("----------------------------------------文件上传成功");
}
事件回溯:和往常一样,写了个一个上传文件的功能,快下班了的时候,前端小伙伴反馈上接口用不了,报错内容贴上:
{
"timestamp": "2024-06-28T00:27:35.969+00:00",
"status": 415,
"error": "Unsupported Media Type",
"path": "/upload"
}
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/octet-stream' is not supported]
当时还是纳闷,之前不都是这么写的,怎么就突然不行了呢?经过一系列的排查,最终用文本对比工具发现唯一的区别就是参数id的注解有区别RequestPart、RequestParam;经过实际验证后,RequestPart注解可以用来接收上传的文件,但是不能接收其它类型的参数,花了1个多小时,问题解决。关于RequestPart和RequestParam注解的其它介绍,请自行搜索。