我尝试将文件从客户端上传到服务器
在客户端,我有一个文件输入
在服务器端我有
private void uploadFile(final FileTransfer fileTransfer) {
String destinationFile = "/home/nat/test.xls";
InputStream fis = null;
FileOutputStream out = null;
byte buf[] = new byte[1024];
int len;
try {
fis = fileTransfer.getInputStream();
out = new FileOutputStream(new File(destinationFile));
while ((len = fis.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
在服务器上创建了一个文件,但它是空的 当我调试时,我可以看到fis不是空的
任何想法?
答案 0 :(得分:0)
以下是我的代码摘录:
try {
File fileData = new File(fileTransfer.getFilename());
// Write the content (data) in the file
// Apache Commons IO: (FileUtils)
FileOutputStream fos = FileUtils.openOutputStream(fileData);
// Spring Utils: FileCopyUtils
FileCopyUtils.copy(fileTransfer.getInputStream(), fos);
// Alternative with Apache Commons IO
// FileUtils.copyInputStreamToFile(fileTransfer.getInputStream(), fileData);
// Send the file to a back-end service
myService.persistFile( fileData );
} catch (IOException ioex) {
log.error("Error with io")
}
return fileTransfer.getFilename(); // this is for my javascript callback fn
Apache Commons IO是一个很好的库,可用于此类操作(我也使用Spring Utils)。如果您没有Spring上下文,请使用Apache的注释替代方法(检查语法,但未验证)。