gpt4 book ai didi

java - Spring Web 响应式客户端

转载 作者:搜寻专家 更新时间:2023-10-31 20:17:16 25 4
gpt4 key购买 nike

我正在尝试使用 Spring Reactive WebClient 将文件上传到 spring Controller 。 Controller 非常简单,看起来像这样:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadFile(
@RequestParam("multipartFile") MultipartFile multipartFile,
@RequestParam Map<String, Object> entityRequest
) {
entityRequest.entrySet().forEach(System.out::println);
System.out.println(multipartFile);
return ResponseEntity.ok("OK");
}

当我将此 Controller 与 cURL 一起使用时,一切正常

curl -X POST http://localhost:8080/upload -H 'content-type: multipart/form-data;' -F fileName=test.txt -F randomKey=randomValue -F multipartFile=@document.pdf

multipartFile 进入正确的参数,其他参数进入 Map。

当我尝试从 WebClient 执行相同的操作时,我卡住了。我的代码如下所示:

    WebClient client = WebClient.builder().baseUrl("http://localhost:8080").build();

MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.set("multipartFile", new ByteArrayResource(Files.readAllBytes(Paths.get("/path/to/my/document.pdf"))));
map.set("fileName", "test.txt");
map.set("randomKey", "randomValue");
String result = client.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.syncBody(map)
.exchange()
.flatMap(response -> response.bodyToMono(String.class))
.flux()
.blockFirst();
System.out.println("RESULT: " + result);

这会导致 400 错误

{
"timestamp":1510228507230,
"status":400,
"error":"Bad Request",
"message":"Required request part 'multipartFile' is not present",
"path":"/upload"
}

有谁知道如何解决这个问题?

最佳答案

所以我自己找到了解决方案。事实证明,Spring 确实需要 Content-Disposition header 来包含一个文件名,以便将上传序列化到 Controller 中的 MultipartFile。

为此,我必须创建一个支持设置文件名的 ByteArrayResource 子类

public class MultiPartResource extends ByteArrayResource {

private String filename;

public MultiPartResource(byte[] byteArray) {
super(byteArray);
}

public MultiPartResource(byte[] byteArray, String filename) {
super(byteArray);
this.filename = filename;
}

@Nullable
@Override
public String getFilename() {
return filename;
}

public void setFilename(String filename) {
this.filename = filename;
}
}

然后可以使用此代码在客户端中使用

WebClient client = WebClient.builder().baseUrl("http://localhost:8080").build();

MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();

map.set("fileName", "test.txt");
map.set("randomKey", "randomValue");
ByteArrayResource resource = new MultiPartResource(Files.readAllBytes(Paths.get("/path/to/my/document.pdf")), "document.pdf");

String result = client.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(map))
.exchange()
.flatMap(response -> response.bodyToMono(String.class))
.flux()
.blockFirst();
System.out.println("RESULT: " + result);

关于java - Spring Web 响应式客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47201419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com