【问题标题】:How to receive multipart request in Spring App如何在 Spring App 中接收多部分请求
【发布时间】:2022-01-04 00:27:34
【问题描述】:

我已经看到了很多来源,也看到了一些关于 SO 的问题,但没有找到解决方案。

我想向我的 Spring 应用发送包含 JSON 对象 Car 和附件的 POST/PUT 请求。

目前我有一个 CarController 可以正确使用 JSON 对象

@PutMapping("/{id}/update")
public void updateCar(@PathVariable(value = "id") Long carId, @Validated @RequestBody Car car) throws ResourceNotFoundException {
    // I can work with received car
}

我还有一个 FileController 可以与 file 正确配合

@PostMapping("/upload")
public void uploadFiles(@RequestParam("file") MultipartFile file) throws IOException {
    // I can work with received file
}

但是我的方法应该如何才能同时使用carfile?这段代码没有提供任何carfile

@PutMapping("/{id}/update")
public void updateCar(@PathVariable(value = "id") Long carId, @Validated @RequestBody Car car, @RequestParam("file") MultipartFile file) throws ResourceNotFoundException, IOException {
    // can not work neither with car nor with file
}

独立控制器在 Postman 测试期间运行良好。但是当我尝试第三个代码时,我得到了这些结果:

【问题讨论】:

    标签: java json spring http multipartform-data


    【解决方案1】:

    您的代码没有任何问题,它可以按原样工作。

    当它是一个多部分请求时,您最终可以通过使用@RequestPart 而不是@RequestParam 和@RequestBody 来提高它的可读性。

    您可以在这篇文章https://www.baeldung.com/sprint-boot-multipart-requests中找到有关多部分请求的更多详细信息

    最重要的是,让它工作/或以正确的方式进行测试:

    当使用 postman 处理多部分请求时,您必须定义每个 RequestPart 的内容类型。

    它是表单数据屏幕中的隐藏列,您可以显示如下:

    选中“Content-Type”框,将出现新列:

    最后,定义每个部分的内容类型。

    【讨论】:

      【解决方案2】:

      是的,我agree with Vladimirmultipart/form-data, @RequestParts 而不是正文和参数:

      @PutMapping(value = "/{id}/update", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
      public void updateCar(@PathVariable(value = "id") Long carId,
              @RequestPart("car") Car car, 
              @RequestPart("file") MultipartFile file) {
         ...
      

      然后在邮递员中:

      • 使用正文>表单数据
      • 当问题:
        • 显示Content-Type 列。
        • 为每个部件设置Content-Type

      【讨论】:

        【解决方案3】:

        方法参数可以使用@RequestMapping注解和@RequestPart注解的consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }字段:

        ResponseEntity<> foo(@RequestPart ParType value, @RequestPart MultipartFile anotherChoice) {
        ...
        

        【讨论】:

          猜你喜欢
          • 2010-09-11
          • 2013-02-10
          • 1970-01-01
          • 1970-01-01
          • 2012-08-12
          • 1970-01-01
          • 1970-01-01
          • 2021-09-19
          • 2020-05-25
          相关资源
          最近更新 更多