我有一个 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
我不确定为什么会发生这种情况,但我配置了这种模式 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
当我在 spring 内部调试时,请求会有点混乱,例如“详细信息”部分甚至没有内容类型,它将为空。
然后我将模式切换为 builder.setMode(HttpMultipartMode.STRICT);然后在 request.getParts() 中,“details”将具有内容类型应用程序 json