我正在尝试将文件上传到在Tomcat7上运行的Spring服务器。这是一个简单的POST请求,代码如下:
@RequestMapping(method = RequestMethod.POST)
public void saveFile(HttpServletRequest request, @RequestParam("file_name") String fileName) {
Logger.getLogger(FileRestAction.class).info("saving file with name " + fileName);
try {
byte[] buf = readFromRequest(request);
String filePath = writeToFile(buf, fileName);
File_ file = new File_(filePath, request.getContentType());
Logger.getLogger(FileRestAction.class).info(request.getContentType() + " " + request.getContentLength());
fService.save(file);
} catch (IOException e) {
Logger.getLogger(FileRestAction.class).error("Failed to upload file. " +
"Exception is: " + e.getMessage());
}
}
private String writeToFile(byte[] buf, String fileName) throws IOException {
String fileBasePath = ConfigurationProvider.getConfig().getString(Const.FILE_SAVE_PATH);
File file = new File(fileBasePath + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(buf);
fos.close();
Logger.getLogger(FileRestAction.class).info("filepath: " + file.getAbsolutePath());
return file.getAbsolutePath();
}
private byte[] readFromRequest(HttpServletRequest request) throws IOException {
InputStream is = request.getInputStream();
byte[] buf = new byte[request.getContentLength()];
is.read(buf);
is.close();
return buf;
}
现在的问题是服务器上的文件只是“完成了一半”,就好像所有字节都不存在一样。例如,如果我发送一个大小为54kB的256x256 .png文件,则写在服务器上的文件大小也是54kB和256x256,但实际图片在开头附近切断(其余为空白)。没有例外被抛出。
经过一些测试后,我发现截止值约为15-20Kb(下图完全上传)。
关于可能导致这种情况的任何想法?
编辑:我根据GreyBeardedGeek的建议更改了readFromRequest方法。它现在如下:
private byte[] readFromRequest(HttpServletRequest request) throws IOException {
InputStream is = request.getInputStream();
int fileLength = (int) request.getContentLength();
byte[] buf = new byte[fileLength];
int bytesRead = 0;
while (true) {
bytesRead += is.read(buf, bytesRead, fileLength - bytesRead);
Logger.getLogger(FileRestAction.class).info("reading file: " + bytesRead + " bytes read");
if (bytesRead == fileLength) break;
}
is.close();
return buf;
}
答案 0 :(得分:2)
不保证InputStream.read会读取您要求的数据量。 您要求的大小是它将读取的最大字节数。
这就是read()方法返回实际读取的字节数的原因。 见http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read(byte [])
所以,答案是多次读取,直到read()返回-1