Returning an Image in a Servlet - Java Servlet JSP

Java examples for Servlet JSP:Servlet

Description

Returning an Image in a Servlet


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ServletContext sc = getServletContext();
    String filename = sc.getRealPath("image.gif");

    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;
    }
    resp.setContentType(mimeType);

    File file = new File(filename);
    resp.setContentLength((int)file.length());

    FileInputStream in = new FileInputStream(file);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }
    in.close();
    out.close();
}

Related Tutorials