java 将文件从Apache HTTP客户端发送到Sping Boot

qyzbxkaa  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(170)

我在尝试将文件从Apache HTTP客户端发送到Sping Boot 服务器时收到以下HTTP 400消息:
已解决[org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文件”不存在]
客户代码:

HttpPost request = new HttpPost(new URIBuilder(URI.create(host)).setPath("api").addParameter("id", id).build());
request.setEntity(MultipartEntityBuilder.create()
        .addPart("file", new InputStreamBody(myStream, MULTIPART_FORM_DATA))
        .build());
CloseableHttpResponse response = httpClient.execute(request);

服务器代码:

@PostMapping(consumes = MULTIPART_FORM_DATA_VALUE)
public void send(@RequestParam("id") String id,
                 @RequestParam("file") MultipartFile file) throws IOException {
// Do something
}

我试着:

  • 服务器:
  • spring.servlet.multipart.enabled=true
  • RequestPart而不是RequestParam
  • 客户端
  • .setMode(BROWSER_COMPATIBLE)
  • addBinaryPart

但还是犯了同样的错误…

n1bvdmb6

n1bvdmb61#

你可以试试这个我在Sping Boot 3中使用MultiPart进行了测试,并取得了成功。
addBinaryBody的底层实现仍然调用addPart。区别在于addBinaryBody在处理过程中使用ContentType.DEFAULT_BINARY。这种ContentType与您的ContentType的差异可能是问题的原因。

try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost("http://localhost:8080/sample/multiPart");

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", new File("someFilePath"));

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);
            System.out.println(response.getCode());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

我的Sping Boot 控制器

@PostMapping(path = "/multiPart", produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity multiPartAPI(@RequestParam(value = "file") MultipartFile file) {
        return ResponseEntity.ok().build();
    }

相关问题