代码在Grails Web应用程序的几个函数中被拆分,但这里有这样的想法
MultipartFile mf = request.getPart();
InputStream is = mf.getInputSteam();
Long size = mf.getSize();
ReadableByteChannel source = Channels.newChannel(inputStream);
FileChannel target = new FileOutputStream(new File('/path/to/file.jpg')).getChannel();
target.transferFrom(source, 0, size);大小正确,InputStream有效,ReadableByteChannel / FileOutputStream已正确创建,但没有任何内容写入输出文件。
我宁愿用经典的'transfer‘方法编码,但我尝试了buffer方法,效果并不好
ByteBuffer buff = ByteBuffer.allocate(bufferSize)
FileChannel target = new FileOutputStream(targetFile).getChannel()
ReadableByteChannel source = Channels.newChannel(inputStream)
while (source.read(buff) >= 0 || buff.position() > 0) {
buff.flip()
target.write(buff)
buff.compact()
}我遗漏了什么?
发布于 2020-06-07 00:51:27
检查返回大小传输的transferFrom()的结果使用try()确保这些流在您期望的时候关闭-特别是对于"new FileOutputStream“/ "FileChannel target”
https://stackoverflow.com/questions/62206765
复制相似问题