从servlet输出图像文件

Dev*_*xit 28 java servlets

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

Õzb*_*bek 51

这是工作代码:

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

}
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 20

  • 将servlet映射到/fileurl-pattern
  • 从磁盘读取文件
  • 把它写给 response.getOutputStream()
  • Content-Type标题设置为image/png(如果它只是pngs)