我有一个上传网络应用程序,我必须在保存图像时计算图像宽度和高度。当我在 Eclipse 中的 tomcat 下运行项目时,一切正常。但是当我在eclipse之外的tomcat中运行它时,我得到了一个NullpointerException。
File tempFile = File.createTempFile("temp", "jpg");
//decode image stream and write to temp file.
BufferedImage bImage = ImageIO.read(new FileInputStream(tempFile ));
int width = bImage.getWidth();
int height = bImage.getHeight();
我看到的不同之处在于,当我在 eclipse 中运行时,临时文件是在 windows 用户临时文件夹下创建的,而在 tomcat 中运行时,临时文件是在 tomcat 临时文件夹下创建的。我已经将文件大小写入日志,而且两次,它们实际上都有大小。
我这里加了更多的代码让大家有经验的可以有我
@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes="application/octet-stream")
@ResponseBody
public String handleStreamUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
InputStream imageEncodeStream = request.getInputStream();
File tempFile = File.createTempFile("-TEMP-", ".temp");
MessageDecoder decoder = new MessageDecoder(
imageEncodeStream, tempFile);
decoder.decode();
String resolution = getResolution();
//generate unique image name and add resolution to image name.
}
解码器代码:
public void decode() throws IOException {
//Some secret decode part here.
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(file);
int bs = 16384;
byte[] buf = new byte[bs];
try {
int off = 0;
for (;;) {
int bytes = in.read(buf, off, bs - off);
if (bytes < 0) { // EOF
if (off > 0) {
fos.write(buf, 0, off);
}
break;
}
if (bytes == 0) {
try {
Thread.sleep(2);
} catch (InterruptedException ignore) {
ignore.printStackTrace();
}
} else if ((off += bytes) == bs) {
fos.write(buf);
off = 0;
}
}
} finally {
fos.close();
}
}
更新:我通过将 maven-compilter-plugin 配置为 1.6 解决了这个问题。然后构建war文件并再次部署到Tomcat。它工作得很好。还不知道根本原因???谁能给我解释一下?