我正在尝试使用 Spring Boot @RestController
上传文件:
@RequestMapping(value = "/register", method = RequestMethod.POST)
public AppResponse registerUserFromApp(
@RequestBody UserInfo userInfo,
@RequestParam(value = "file", required = false) CommonsMultipartFile file,
@RequestParam(value = "inviteCode", required = false) String inviteCode){
根据这个定义,我尝试了这个 Postman 请求:
这不起作用。
我尝试将其添加到我的 RequestMapping
中:
@RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "multipart/form-data")
这给了我同样的错误。
对于userInfo
,我按照another SO answer的建议在表单数据字段本身中以JSON形式发送值。 。不起作用,同样的错误。
正如其他一些 SO 答案中所建议的,我还确保我没有在 Postman 中发送任何 header 。
我也尝试在 application.properties
中添加以下属性:
spring.http.multipart.enabled=false
同样的错误。我还尝试了 MultipartFile
而不是 CommonsMultipartFile
,没有任何区别。
我做错了什么?我还想在请求中将图像作为 File 和 UserInfo 对象发送。 postman 的例子将非常感激。
最佳答案
带有自定义对象的多部分表单数据将被接受为字符串。所以你的 Controller 将如下所示。
@RequestMapping(value = "/register", method = RequestMethod.POST)
public AppResponse registerUserFromApp(
@RequestBody String userInfo,
@RequestParam(value = "file", required = false) CommonsMultipartFile file,
@RequestParam(value = "inviteCode", required = false) String inviteCode){
ObjectMapper obj=new ObjectMapper();
UserInfo userInfo=obj.readValue(clientData, UserInfo.class);
}
您必须使用 ObjectMapper 将 String 转换为 pojo。希望这会有所帮助。
关于spring-boot - 在 Spring Boot REST API 中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074213/