How do I serve an image file in the filesystem from a servlet?
Asked
Active
Viewed 4,123 times
3
-
1What is your application server ? Some offers a clean way to define a web app to publish static content, eg weblogic : http://blogs.oracle.com/middleware/2010/06/publish_static_content_to_weblogic.html – RealHowTo Feb 05 '11 at 00:05
-
1And Tomcat: http://stackoverflow.com/questions/1502841/reliable-data-serving/2662603#2662603 – BalusC Feb 05 '11 at 00:26
2 Answers
2
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();
}

aioobe
- 413,195
- 112
- 811
- 826
-
works for my site, but we do get about 15 million page views a month so it needs some optimizing – sadgas Feb 04 '11 at 23:36
-
Hey aioobe, your link is now broken which means this answer has lost all use. `:(` – Matt Ball Oct 30 '12 at 03:02
-
Thanks Matt. It would be nice if SO had a service for notifying authors if/when their links break. Heck, why not add a cache of each web-page being linked to. – aioobe Oct 30 '12 at 10:34
0
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.

irreputable
- 44,725
- 9
- 65
- 93