【问题标题】:Output an image file from a servlet [duplicate]从 servlet 输出图像文件 [重复]
【发布时间】:2012-01-27 06:22:04
【问题描述】:

如何在 servlet 中提供存储在我硬盘上的图像?
例如:
我有一个图像存储在路径 'Images/button.png' 中,我想在 URL file/button.png 的 servlet 中提供它。

【问题讨论】:

  • 您知道设置为image/pngContent-Type 的重要性或以下答案中提到的任何您需要的内容吗?

标签: java servlets


【解决方案1】:
  • 将 servlet 映射到 /file url 模式
  • 从磁盘读取文件
  • 写信给response.getOutputStream()
  • Content-Type 标头设置为image/png(如果只是png)

【讨论】:

    【解决方案2】:

    这是工作代码:

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

    【讨论】:

      【解决方案3】:

      这是另一种非常简单的方法。

      File file = new File("imageman.png");
      BufferedImage image = ImageIO.read(file);
      ImageIO.write(image, "PNG", resp.getOutputStream());
      

      【讨论】:

      • 这是非常低效的,因为它不必要地将图像解析为BufferedImage 对象。如果您不想操作图像(调整大小、裁剪、变换等),则不需要此步骤。最快的方法是将未修改的字节从图像输入流式传输到响应输出。
      猜你喜欢
      • 2014-03-21
      • 2016-07-22
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多