我们有一个接受图片上传的servlet。有时,当上传源自我们的iPhone客户端(片状连接)时,保存的图像可能会部分或完全变灰。我怀疑这是由于连接过早终止而servlet最终处理不完整的图像。
对此最好的补救措施是什么?有没有办法在处理之前查看整个图像是否已上传?我应该使用HTTP Content-Length标头并比较使用此号码上传的内容吗?
谢谢!
上下文的一些代码:
@Path("images/")
@POST
@Consumes("image/*")
@Produces({"application/xml", "application/json"})
public AbstractConverter postImage(byte[] imageData) {
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(new ByteArrayInputStream(imageData));
} catch (Exception e) {
}
if (bufferedImage == null) {
throw new PlacesException("Image data not provided or could not be parsed", Response.Status.BAD_REQUEST);
}
...
BufferedImage scaledImage = ImageTool.scale(bufferedImage, imageSize);
BufferedImage thumbnail = ImageTool.scale(bufferedImage, thumbnailSize);
//Save image and thumbnail
File outputfile = new File(path);
ImageTool.imageToJpegFile(scaledImage, outputfile, 0.9f);
File tnOutputfile = new File(thumbnailPath);
ImageTool.imageToJpegFile(thumbnail, tnOutputfile, 0.9f);
...
public static void imageToJpegFile(RenderedImage image, File outFile, float compressionQuality) throws IOException {
//Find a jpeg writer
ImageWriter writer = null;
Iterator<ImageWriter> iterator = ImageIO.getImageWritersByFormatName("jpeg");
if (iterator.hasNext()) {
writer = iterator.next();
} else {
throw new RuntimeException("No jpeg writer found");
}
//Set the compression quality
ImageWriteParam params = writer.getDefaultWriteParam();
params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
params.setCompressionQuality(compressionQuality);
//Write to the out file
ImageOutputStream ios = null;
try {
ios = ImageIO.createImageOutputStream(outFile);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), params);
} finally {
writer.dispose();
if (ios != null) {
try {
ios.flush();
} catch (Exception e) {
}
try {
ios.close();
} catch (Exception e) {
}
}
}
}
答案 0 :(得分:0)
似乎上传未正确完成。
正如您自己指出的那样,最好的办法是使用HTTP Content-Length
标头检查是否已收到所有数据。如果没有,请丢弃图像。