使用apache http客户端使用multipart上传文件到spring boot

问题描述 投票:0回答:1

我有一个 Spring Boot 应用程序,它有这样的端点

@PostMapping("/")
public ResponseEntity<FileUploadResponseDto> upload(@RequestPart("details") FileUploadDto fileUploadDto,@RequestParam("file") MultipartFile file){
  try {
      return ResponseEntity.ok( fileUploadService.uploadFile(fileUploadDto,file));
  }catch (Exception e){
      return ResponseEntity.status(406).body(new FileUploadResponseDto(false,e.getMessage()));
  }
};

使用邮递员时一切正常。 这是邮递员的例子

但是当我尝试使用 http apache 客户端时,Spring Boot 返回不支持 application/octet-stream

我在这里做错了什么?

编辑

编写 apache 客户端代码

String json = mapToJson(Map.of("name",(String)file[1],"lastname",    

(String)file[2],"createTime",(String)file[3]));
       final MultipartEntityBuilder builder  =                               
       MultipartEntityBuilder.create();

       builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
       builder.addTextBody("details",json,ContentType.APPLICATION_JSON);
       builder.addBinaryBody("file",(File)file[4],ContentType.APPLICATION_OCTET_STREAM,((File)file[4]).getName());

       final HttpPost httpPost = new HttpPost("http://"+host+":"+port+"/api/v1/upload/");
       try(CloseableHttpClient client = HttpClientBuilder.create().build()) {

           final HttpEntity entity = builder.build();
           httpPost.setEntity(entity);
           HttpResponse httpResponse = client.execute(httpPost);

           System.out.println(httpResponse);

       } catch (IOException e) {
           throw new RuntimeException(e);
       }

这是我收到的消息/回复

HttpResponseProxy{HTTP/1.1 415 [接受:application/json,application/*+json,内容类型:application/json,传输编码:分块,日期:Sun,2024 年 2 月 11 日 22:02:27 GMT,Keep-活动:超时 = 60,连接:保持活动] ResponseEntityProxy{[Content-Type:application/json,Chunked:true]}}

解决方案:

我不确定为什么会发生这种情况,但我配置了这种模式 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

当我在 spring 内部调试时,请求会有点混乱,例如“详细信息”部分甚至没有内容类型,它将为空。

然后我将模式切换为 builder.setMode(HttpMultipartMode.STRICT); 然后在 request.getParts() 中,“details”将具有内容类型应用程序 json

spring spring-boot httpclient multipart
1个回答
0
投票

我不确定为什么会发生这种情况,但我配置了这种模式 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

当我在 spring 内部调试时,请求会有点混乱,例如“详细信息”部分甚至没有内容类型,它将为空。

然后我将模式切换为 builder.setMode(HttpMultipartMode.STRICT);然后在 request.getParts() 中,“details”将具有内容类型应用程序 json

© www.soinside.com 2019 - 2024. All rights reserved.