我正在尝试将文件上传到在 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;
}
现在的问题是服务器上的文件只是“完成了一半”,就好像所有字节都不存在一样。例如,如果我发送一个 256x256 的 .png 文件,大小为 54kB,写在服务器上的文件也是 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;
}
最佳答案
InputStream.read 不能保证读取您请求的数据量。 您要求的大小是它将读取的最大字节数。
这就是 read() 方法返回实际读取的字节数的原因。 参见 http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read(byte[])
所以,答案是多次读取,直到read()返回-1
关于java - 文件仅部分上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9446208/