【发布时间】:2012-01-27 06:22:04
【问题描述】:
如何在 servlet 中提供存储在我硬盘上的图像?
例如:
我有一个图像存储在路径 'Images/button.png' 中,我想在 URL file/button.png 的 servlet 中提供它。
【问题讨论】:
-
您知道设置为
image/png的Content-Type的重要性或以下答案中提到的任何您需要的内容吗?
如何在 servlet 中提供存储在我硬盘上的图像?
例如:
我有一个图像存储在路径 'Images/button.png' 中,我想在 URL file/button.png 的 servlet 中提供它。
【问题讨论】:
image/png 的Content-Type 的重要性或以下答案中提到的任何您需要的内容吗?
/file url 模式response.getOutputStream()
Content-Type 标头设置为image/png(如果只是png)【讨论】:
这是工作代码:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext cntx= req.getServletContext();
// Get the absolute path of the image
String filename = cntx.getRealPath("Images/button.png");
// retrieve mimeType dynamically
String mime = cntx.getMimeType(filename);
if (mime == null) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mime);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
out.close();
in.close();
}
【讨论】:
这是另一种非常简单的方法。
File file = new File("imageman.png");
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, "PNG", resp.getOutputStream());
【讨论】:
BufferedImage 对象。如果您不想操作图像(调整大小、裁剪、变换等),则不需要此步骤。最快的方法是将未修改的字节从图像输入流式传输到响应输出。