我们有一个接受图像上传的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) {
}
}
}
}
最佳答案
似乎上传未正确完成。
正如您自己指出的那样,最好的选择是使用HTTP Content-Length
标头检查是否已接收到所有数据。如果不是,则丢弃图像。