I want to display the image located in my local drive. I am using sun java app server 8. For example If I generate a file abc.jpg dynamically and store it in c:\abc.jpg, then how could I use it in jsp or servlets? How to display it in the jsp or servlet pages? I know giving the path c:\abc.jpg in coding to display image wont work , because it is out of webserver..
views:
235answers:
2how to use the image file located in local drive, for printing it in jsp page or servlet page?
Basically just create a Servlet
which gets an InputStream
of it with help of FileInputStream
and writes it to the OutputStream
of the HttpServletResponse
along with a correct set of response headers with at least the content-type
. Finally call this servlet in the src
attribute of the <img>
element along with the file identifier as request parameter or pathinfo. E.g.:
File file = new File("c:/abc.jpg");
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[10240];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
You can find here a complete basic example: http://balusc.blogspot.com/2007/04/imageservlet.html
Maybe everybody is misunderstanding the question.
If the images are on your local drive and you want your Web server to serve them up to the world, then as a first step you need to upload them to your Web server.
That done, you can use URLs in <img>
tags to refer to their location on the server.