从servlet输出一个图像文件

28

如何在servlet中提供存储在硬盘上的图片?
例如:
我有一张存储在路径'Images/button.png'中的图片,并且我想在servlet中使用URL file/button.png 来提供这张图片。


你知道Content-Type的重要性吗?在下面的答案中提到,它应该设置为image/png或任何你需要的类型。 - Lion
3个回答

54

这是可用的代码:

 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();

}

21
  • 将一个servlet映射到/file的url-pattern
  • 从磁盘读取文件
  • 将其写入response.getOutputStream()
  • 如果只有png格式,设置Content-Type头为image/png

1
这是另一种非常简单的方法。
File file = new File("imageman.png");
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, "PNG", resp.getOutputStream());

3
这种方法非常低效,因为它不必要地将图像解析为BufferedImage对象。如果您不想操作图像(调整大小、裁剪、变换等),则不需要此步骤。最快的方式是直接从图像输入流式传输未经修改的字节到响应输出。 - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接