【问题标题】:Spring RestTemplate POST upload multiple filesSpring RestTemplate POST 上传多个文件
【发布时间】:2020-03-18 15:44:37
【问题描述】:

假设我有一个如下所示的端点:

  @PostMapping(
      value = "/something",
      consumes = MULTIPART_FORM_DATA_VALUE,
      produces = APPLICATION_JSON_VALUE)
  public SomeDTO post2Files(
      @RequestPart("file1") MultipartFile file1,
      @RequestPart("file2") MultipartFile file2 {

在另一项服务中,我想从文件系统中读取一个文件并重新发送它,而 file2 实际上是一个字符串,我想通过 RestTemplate 作为文件传递。 我试过这样的事情:

   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.MULTIPART_FORM_DATA);
   MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
   body.add("file1", new FileSystemResource(somePath));
   body.add("file2", new ByteArrayResource(someString.getBytes()));
   restTemplate.postForObject("/something", new HttpEntity<>(body, headers), SomeDTO.class)

它不起作用,我不知道为什么。我得到 400。我应该怎么做才能使请求通过?

【问题讨论】:

    标签: spring spring-boot file-upload multipartform-data resttemplate


    【解决方案1】:

    想通了。 这是解决方案:

    body.add("dataSchema", new ByteArrayResource(someString.getBytes()) {
                @Override
                public String getFilename() {
                    return "file2";
                }
            });
    

    它不起作用,因为文件名与@RequestPart 不匹配。

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多