【问题标题】:Multipart file Sping Boot多部分文件 Spring Boot
【发布时间】:2021-05-29 03:43:44
【问题描述】:

我正在使用 MultipartFile 在 Web 应用程序中上传文件。是否可以让用户(发布者)在上传的文件中添加一些描述和标签,以便稍后用于搜索?

【问题讨论】:

    标签: java spring-boot thymeleaf


    【解决方案1】:

    您可以在POST 请求正文中添加该字段:

    @PostMapping(value = "/upload", consumes = MULTIPART_FORM_DATA_VALUE)
    ResponseEntity<Void> uploadFile(
            @RequestParam("files") List<MultipartFile> files,    
            @RequestParam("descr") String description
    );
    

    并发送请求,例如:

    【讨论】:

      【解决方案2】:

      您可以使用两种媒体类型:

      consumes = { MediaType.APPLICATION_JSON_VALUE,MediaType.MULTIPART_FORM_DATA_VALUE })

      我们需要将给定的参数作为标签和多部分文件传递。在这里,请确保我们只能传递 String + file 而不是 POJO + file。

      @RequestPart(“tag”) String tag, @RequestPart(“file”) List&lt;MultipartFile&gt; file

      然后在Service层使用ObjectMapper将String转成Json。

      Tag tagPojo = new ObjectMapper().readValue(tag, Tag.class);

      所以它看起来像:

      @PostMapping(value = "/send", consumes = { MediaType.APPLICATION_JSON_VALUE,MediaType.MULTIPART_FORM_DATA_VALUE })
      public void upload(@RequestPart(“tag”) String tag, @RequestPart(“file”) List<MultipartFile> file) {
      Tag tagPojo = new ObjectMapper().readValue(tag, Tag.class);
      }
      

      【讨论】:

        猜你喜欢
        • 2014-10-31
        • 2014-05-01
        • 2022-10-22
        • 1970-01-01
        • 2019-11-10
        • 1970-01-01
        • 2018-08-20
        • 2019-07-24
        • 1970-01-01
        相关资源
        最近更新 更多