从servlet中的文件系统提供静态图像文件?

时间:2011-02-04 23:00:22

标签: java image servlets filesystems

如何从servlet中提供文件系统中的映像文件?

2 个答案:

答案 0 :(得分:2)

请查看此处: Example Depot: Returning an Image in a Servlet 链接损坏。下面插入Wayback Machine副本:

// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the absolute path of the image
    ServletContext sc = getServletContext();
    String filename = sc.getRealPath("image.gif");

    // Get the MIME type of the image
    String mimeType = sc.getMimeType(filename);
    if (mimeType == null) {
        sc.log("Could not get MIME type of "+filename);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Set content type
    resp.setContentType(mimeType);

    // Set content size
    File file = new File(filename);
    resp.setContentLength((int)file.length());

    // Open the file and output streams
    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);
    }
    in.close();
    out.close();
}

答案 1 :(得分:0)

除非图像位于webapp目录下,否则servlet规范没有明确的方法,这是一种耻辱。 Servlet容器通常不会建议其专有的方法来执行此操作。显然,容器必须这样做才能提供文件,为什么不暴露这些功能呢?为什么不是HttpServletResponse.sendFile(File)

您最好的办法是创建符号链接,以便您的文件显示在webapp目录下。