gpt4 book ai didi

java - 发送收到的 spring FilePart 而不保存

转载 作者:行者123 更新时间:2023-12-04 11:34:13 28 4
gpt4 key购买 nike

我需要使用 WebClient 将 RestController 中收到的 FilePart 发送到 API,
我怎样才能做到这一点?
找到一个示例,将图像保存到磁盘。

private static String UPLOAD_ROOT = "C:\\pics\\";

public Mono<Void> checkInTest(@RequestPart("photo") Flux<FilePart> photoParts,
@RequestPart("data") CheckInParams params, Principal principal) {
return saveFileToDisk(photoParts);
}

private Mono<Void> saveFileToDisk(Flux<FilePart> parts) {
return parts
.log("createImage-files")
.flatMap(file -> {
Mono<Void> copyFile = Mono.just(Paths.get(UPLOAD_ROOT, file.filename()).toFile())
.log("createImage-picktarget")
.map(destFile -> {
try {
destFile.createNewFile();
return destFile;
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.log("createImage-newfile")
.flatMap(file::transferTo)
.log("createImage-copy");

return Mono.when(copyFile)
.log("createImage-when");
})
.log("createImage-flatMap")
.then()
.log("createImage-done");
}
然后再次阅读并发送到另一个服务器
.map(destFile -> {
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
try {
map.set("multipartFile", new ByteArrayResource(FileUtils.readFileToByteArray(destFile)));
} catch (IOException ignored) {
}
map.set("fileName", "test.txt");
WebClient client = WebClient.builder().baseUrl("http://localhost:8080").build();

return client.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.syncBody(map)
.exchange(); //todo handle errors???
}).then()
有没有办法避免保存文件?

最佳答案

我会提到@Abhinaba Chakraborty 的解决方案
提供于 https://stackoverflow.com/a/62745370/4551411

Probably something like this:

  @PostMapping(value = "/images/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<ResponseEntity<Void>> uploadImages(@RequestPart("files") Flux<FilePart> fileParts) {
return fileParts
.flatMap(filePart -> {
return webClient.post()
.uri("/someOtherService")
.body(BodyInserters.fromPublisher(filePart.content(), DataBuffer.class))
.exchange()
.flatMap(clientResponse -> {
//some logging
return Mono.empty();
});
})
.collectList()
.flatMap(response -> Mono.just(ResponseEntity.accepted().build()));
}

This accepts MULTIPART FORM DATA where you can attach multiple image files and upload them to another service.

关于java - 发送收到的 spring FilePart 而不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655646/

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