【问题标题】:Spring Boot REST multi part request (file + json) throwing 415 Unsupported Media Type exceptionSpring Boot REST 多部分请求(文件 + json)抛出 415 Unsupported Media Type 异常
【发布时间】:2020-01-02 13:30:11
【问题描述】:

我使用的是 Spring Boot 版本 = 1.5.2.RELEASE。 当我发送带有 json 对象的多部分文件以在邮递员中上传文件时,它会抛出 415 Unsupported Media Type 异常。

这是我的控制器类。

@RestController
@RequestMapping("/service/promotion/")
public class JobController {
....
....
....
@RequestMapping(value = "/job/test", method = RequestMethod.POST, produces = "application/json", consumes = "multipart/form-data")
public ResponseEntity<Object> createJobTest(@Valid @RequestBody JobRequest jobRequest,
            @RequestParam(value = "file", required = false) MultipartFile multiPartFile) throws Exception {

我的 json 请求类。

 public class JobRequest {
        private String campaignKey;
        private String communicationId;
        private Integer channelId;
        private String templateType;
        private String subject;
        private String frequencyControl;
        private Integer leadsRequested;
        private String keywordRelavance;
        private String scheduledAt;
        private String file;
        private String updatedBy;
        
        //getter and setter
    }   

邮递员中的 JSON 请求

邮递员中的多部分文件请求

标题内容类型

但是当我从控制器类和邮递员中删除消耗时

@RequestMapping(value = "/job/test", method = RequestMethod.POST, produces = "application/json")

然后调试器进入控制器类,但多部分文件值出现 null 在请求对象中,例如

我在 Google 上搜索了很多,已经发布了很多类似的问题,但没有一个对我有帮助。 请帮我解开这个谜。

谢谢。

【问题讨论】:

  • 我也有同样的问题。找到问题了吗?

标签: json spring-boot multipartform-data


【解决方案1】:

查看File upload along with other object in Jersey restful web service

另一种方法是您可以在文本中传递整个对象,就像在表单数据中传递文件并在对象中转换一样。

 @RequestMapping(value = "/uploadDocs", method = RequestMethod.POST, produces = "application/json", consumes = "multipart/form-data")
    public ResponseEntity<Object> methodName(@RequestParam("files") MultipartFile file, @RequestParam("anyKeyName") String objectString)

你可以使用

将字符串转换为对象
Class object = new ObjectMapper().readValue(objectString, Class.class);

【讨论】:

  • 谢谢你的回复,我也做了你上面提到的。它适用于 PUT 请求而不是 POST 请求。知道为什么会这样吗?
  • 我仍然面临同样的问题,任何人都知道出了什么问题。
  • Postman for Linux 版本 6.7.1 linux 4.15.0-58-generic / x64
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 2012-04-19
  • 2012-07-14
相关资源
最近更新 更多