开发者

Serve a static image file from the filesystem in a servlet?

How do I serve a开发者_运维知识库n image file in the filesystem from a servlet?


Have a look over here: Example Depot: Returning an Image in a Servlet Link broken. Wayback Machine copy inserted below:

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


Well it's kind of a shame that servlet spec doesn't have a clear way to do it, unless the image is located under the webapp dir. Servlet containers do not usually advise their proprietary ways to do this either. Obviously a container must do this to serve files, why doesn't it expose the functionality? Why not a HttpServletResponse.sendFile(File)?

Your best bet is to create symlinks so your files appears be to under webapp dir.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜