【问题标题】:Spring 5 - Read JSON or MultipartFileSpring 5 - 读取 JSON 或 MultipartFile
【发布时间】:2019-05-07 05:06:20
【问题描述】:

我遇到了一个看起来非常简单的问题。我有一个 http 端点,它应该接受 JSON 正文或上传的文件。

这里是控制器方法的定义:

@PostMapping(value = "/api/endpoint")
public CompletableFuture<ResponseEntity<Void>> createResource(
       @RequestParam(name = "file", required = false) MultipartFile file,
       @RequestBody(required = false) Command command){
}

Command 是一个 POJO 类,带有用于反序列化的 Jackson 注释。 当我使用 Content-Type: application/json 传递 JSON 正文时,它工作正常。但是当我使用 Content-Type: multipart/form-data 传递文件时,我得到 415 Unsupported Media Type。

这是仅传递 JSON 正文时的原始 http 请求。

POST /api/devices?= HTTP/1.1
Host: localhost:8080
Content-Type: application/json
cache-control: no-cache
{"foo": "bar"}------WebKitFormBoundary7MA4YWxkTrZu0gW--

任何想法是什么导致了这个,谢谢。

【问题讨论】:

  • 只是为了确定,你配置了 org.springframework.web.multipart.commons.CommonsMultipartResolver 吗?

标签: spring-mvc spring-boot spring-rest


【解决方案1】:

试试下面的代码。

@PostMapping(value = "/api/endpoint",consumes = {"multipart/form-data"})
public CompletableFuture<ResponseEntity<Void>> createResource(
       @RequestPart("file") MultipartFile file,
       @RequestPart Command command){
}

【讨论】:

  • 现在我没有得到 415,但是当我传递 json 时命令变量为空。
  • 请分享您用于测试的 Post 请求
  • 更新帖子。顺便说一句。当我删除 required = false 时。 Spring 抛出请求处理失败;嵌套异常是 org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request;嵌套异常是 java.lang.IllegalStateException: UT010057: multipart config was not present on Servlet
  • 您的发帖请求不正确。 Content-Type 不能是 application/json。您的发布请求应该类似于 POST localhost:8080/api/endpoint Content-Type: multipart/form-data;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data;名称="文件"; filename="abc.csv" Content-Type: text/csv
  • 如果我发布 JSON 正文,为什么它不能是 application/json?
【解决方案2】:

您可能需要两个具有不同参数和注释的独立方法。当然,每个人都可以为他们的共同行为调用一个共享的内部方法。

【讨论】:

    猜你喜欢
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2020-06-21
    • 2014-12-11
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多