在下面的代码片段中,我尝试使用 Spring 的 Part 对象提取文件的内容(发送到给定的服务)并将其转换为字符串。
问题是它跳过了映射器函数,并且映射器函数内的代码不会像 filePartMono 的内容为空一样执行,但是当我在运行时检查对象时,它的存储字段包含文件的数据。
public void parseFilePart(Part filePartMono) {
filePartMono.content().map(dataBuffer -> {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
DataBufferUtils.release(dataBuffer);
String fileContent = new String(bytes, StandardCharsets.UTF_8);
});
}
最佳答案
org.springframework.http.codec.multipart.Part.content()
返回 Flux<DataBuffer>
,这意味着在您订阅此 Publisher
之前不会发生任何事情。 .
如果你的代码可以以阻塞方式执行而不会导致错误,你可以像这样重构它以获得 String 结果:
public void parseFilePart(Part filePartMono) {
List<String> parts =
filePartMono.content()
.map(dataBuffer -> {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
DataBufferUtils.release(dataBuffer);
return new String(bytes, StandardCharsets.UTF_8);
})
.collectList()
.block();
//do what you want here with the Strings you retrieved
}
如果您确定 Flux<DataBuffer>
将始终发出 1 个单曲 DataBuffer
,您可以替换 .collectList().block()
与 .blockFirst()
并获得String
结果而不是 List<String>
.
如果您的代码无法以阻塞方式执行,那么您可以像这样重构它:
public void parseFilePart(Part filePartMono) {
filePartMono.content()
.map(dataBuffer -> {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
DataBufferUtils.release(dataBuffer);
return new String(bytes, StandardCharsets.UTF_8);
})
.subscribe(resultString -> {
//do what you want with the result String here
});
}
P.S.我没有测试你的实现来转换 DataBuffer
至String
,因此您可能必须仔细检查它是否已实际调用
关于java - 无法将部件的内容 (Flux<DataBuffer>) 读取到单个字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66213659/