我正在构建一个小型图像缩放工具,用户首先将图像上传到网页,并在提交该表单时显示一个放大的图像以便保存。但是当用户发送对具有不同宽度和高度参数的相同图像的请求时,问题就出现了。在这种情况下,我在servlet中设置的内容disposing头似乎不起作用,第二个请求之后的图像仅与servlet的类名一起发送,而不是我在内容配置中提到的文件名和扩展名报头中。
response.setContentType("image/jpeg");
response.setHeader("Content-disposition","inline;filename="+filename);
我也尝试在编写器本身硬编码,但我使用的那个似乎没有任何文件名参数
private void doDownload(HttpServletResponse resp, BufferedImage bump,
InputStream filecontent) throws IOException {
//http://stackoverflow.com/questions/9340569/jpeg-image-with-wrong-colors
OutputStream out = resp.getOutputStream();
Iterator<ImageWriter> iter = ImageIO
.getImageWritersByMIMEType("image/jpeg");
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);
ImageOutputStream imgOut = new MemoryCacheImageOutputStream(out);
writer.setOutput(imgOut);
IIOImage image = new IIOImage(bump, null, null);
writer.write(null, image, iwp);
out.flush();
out.close();
writer.dispose();
}
有什么办法可以在将图像文件名写入输出流时设置它的文件名吗?
答案 0 :(得分:0)
在此Class中声明一个Static Integer变量。
private static int fileno=0;
private void doDownload(HttpServletResponse resp, BufferedImage bump,
InputStream filecontent) throws IOException {
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(1);
String OUTPUTFILE = "C:/Users/Harish/Desktop/jpegFile"+fileno++;
File file = new File(OUTPUTFILE);
//Your fileName will be jpegFile0; and next time jpegFile1 and so on.
FileImageOutputStream imgOut = new FileImageOutputStream(file);
writer.setOutput(imgOut);
IIOImage image = new IIOImage(bump, null, null);
writer.write(null, image, iwp);
writer.dispose();
}