【问题标题】:Create a REST API to upload Multipart file data in spring boot在spring boot中创建一个REST API来上传Multipart文件数据
【发布时间】:2019-09-18 02:29:05
【问题描述】:

我创建了一个 rest API 来接受MULTIPART_FORM_DATA,如下所示。但是,一旦我使用 Postman 访问该服务,我就会收到 HTTP 状态 415 – 不支持的媒体类型异常

@POST
@Path("/fileupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public String uploadfile(@RequestParam(value = "file") MultipartFile file) {

    System.out.println(file.getName());

    return "Success String";
}

这里有什么问题?要使用MediaType.MULTIPART_FORM_DATA,我需要进行任何修改吗? 在 Postman 中,我在 BODY 中附加了一个文本文件并点击了端点。内容类型设置为“multipart/form-data”

【问题讨论】:

标签: java spring rest spring-boot postman


【解决方案1】:

您似乎对带有 Rest easy implementation 的 Spring rest API 感到困惑。

  1. 在 Resteasy, 处理上传文件的正常方法是通过 MultipartFormDataInput 或将上传的文件映射到 通过@MultipartForm 的 POJO 类

https://www.mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/

How to POST a multipart/form data with files programatically in a REST API

  1. 如果你想使用弹簧休息的方法,参考这里 Multipart File upload Spring Boot

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      您可能导入了不同的注释。 试试这个方法

      import org.springframework.web.bind.annotation.*;
      
      import static org.springframework.http.MediaType.*;
      
      @PostMapping(value = "/fileupload", consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
      public String uploadfile(@RequestParam(value = "file") MultipartFile file) {
          System.out.println(file.getName());
          return "Success String";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-08
        • 2018-04-04
        • 2017-08-08
        • 2015-03-26
        • 2014-04-19
        • 2021-06-06
        • 1970-01-01
        • 2016-12-14
        相关资源
        最近更新 更多