代码是通过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()
}
我想念的是什么?
检查返回大小为transferrde的transferFrom()的结果,请使用try()以确保在期望时关闭这些流-特别是对于“ new FileOutputStream” /“ FileChannel target”而言]]