在下面的代码片段中,我试图使用Spring的Part对象提取文件的内容(发送到给定的服务),并将其转换为字符串。
问题是它跳过了mapper函数,mapper函数内部的代码不像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>
总是释放一个单独的DataBuffer
,你可以用.blockFirst()
代替.collectList().block()
,得到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
});
}
注:我没有测试你的实现转换DataBuffer
到String
,所以你可能要仔细检查,现在它实际上调用