How to serve an image, stored on my hard drive, in a servlet?
For Example:
I have an image stored in path 'Images/button.png'
and I want to serve this in a servlet with the URL file/button.png
.
Asked
Active
Viewed 9.4k times
28

Devashish Dixit
- 1,153
- 6
- 16
- 25
-
Do you know the importance of `Content-Type` that is set to `image/png` or whatever you need as mentioned in the following answer? – Lion Dec 24 '11 at 09:45
3 Answers
54
Here is the working code:
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();
}

Jama A.
- 15,680
- 10
- 55
- 88
21
- map a servlet to the
/file
url-pattern - read the file from disk
- write it to
response.getOutputStream()
- set the
Content-Type
header toimage/png
(if it is only pngs)

Bozho
- 588,226
- 146
- 1,060
- 1,140
1
Here's another very simple way.
File file = new File("imageman.png");
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, "PNG", resp.getOutputStream());

Gary Eberhart
- 150
- 1
- 7
-
3This is very inefficient as it unnecessarily parses the image into a `BufferedImage` object. This step is not needed if you don't want to manipulate the image (resize, crop, transform, etc). The fastest way is to just stream the bytes unmodified from the image input to the response output. – BalusC Jul 20 '16 at 07:26