The src
attribute of the HTML <img>
element should point to an URL, not to a local disk file system path. The HTML page is namely downloaded from server machine to client machine and parsed at the client machine. Any URL's which occurs in the HTML page (e.g. Javascripts, Stylesheets, Images, etc) would be re-invoked from the client side on. If the client encounters a local disk file system path, it will try to search for the file at its own local disk file system. This ain't going to work if the server and the client are physically different machines.
In your particular case, there are two ways to solve this problem.
Add a new webapplication context to your servletcontainer with the pure purpose to serve static files. It's unclear which servletcontainer you're using, but it it's Tomcat, then all you basically need to do is to add the following Context
element to /conf/server.xml
:
<Context docBase="/path/to/images" path="/images" />
This way they will be accessible by http://example.com/images/....
.
Create a Servlet
class which uses java.io.File
to get an InputStream
of the image file and writes it to the OutputStream
of the response. You can use request parameters or pathinfo to identify the image. Here's a basic example of such a servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String filename = URLDecoder.decode(request.getPathInfo(), "UTF-8");
File file = new File("/path/to/images", filename);
response.setContentType(getServletContext().getMimeType(file.getName()));
response.setContentLength(file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[8192];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
}
Map it in web.xml
on an url-pattern
of for example /images/*
. This way you can access images by for example http://example.com/images/filename.jpg
.
<img src="/images/filename.jpg">
Another image servlet example can be found here.