提问人:Faiz 提问时间:10/17/2023 最后编辑:Brian Tompsett - 汤莱恩Faiz 更新时间:10/19/2023 访问量:39
如何为上传文件以及同时发送 json 有效负载发出 http post 请求
How to make a http post request for Uploading a file as well as sending json payload simultaneously
问:
我一直在尝试上传文件并使用springboot通过Postman发送一些数据,但由于某种原因,但我不知道发生了什么,它不起作用,我尝试使用该方法,但它不起作用,我也使用过注释,但它不起作用@RequestParam("file") MultipartFile file and @RequestBody MyClass myClass
@requestPart
我正在使用以下代码,但我不知道这有什么问题?
@RestController
public class FileUpload {
@PostMapping("/upload")
public String register(@RequestPart("file") MultipartFile file , @RequestBody User
user
String uploadDirectory = "myDirectory";
if (file.isEmpty() || file == null) {
return "file cannot be null or empty";
}
try {
File dir = new File(uploadDirectory);
if (!dir.exists()) {
dir.mkdir();
}
String originName = file.getOriginalFilename();
System.out.println(originName);
File destination = new File(uploadDirectory + File.separator + originName);
if(destination.exists()) {
return "file with same name already exists";
}else {
file.transferTo(destination);
}
return "successfully file uploaded using userID : " + user.getUserid();
} catch (IOException e) {
e.printStackTrace();
return "upload failed";
}
}
我不能同时执行这两个操作吗,我认为应该可以吗?
答:
0赞
BugHunter
10/17/2023
#1
我认为您需要将 @RequestPart 用于文件和 json 有效负载。
public String register(@RequestPart("file") MultipartFile file, @RequestPart("user") User user) {
your original code here ...
}
评论
0赞
Faiz
10/17/2023
我完全按照你说的做了,但它仍然不起作用,它说“org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException:请求不包含 multipart/form-data 或 multipart/mixed 流,内容类型标头是 application/json
0赞
BugHunter
10/17/2023
尝试将两者的 @to @ 更改为RequestPart
RequestParam
0赞
BugHunter
10/17/2023
此外,请确保从 Postman 发送的请求与@RequestParam注释中的参数名称匹配,并相应地包含文件和用户数据
评论