How to use image file located on local disk to print it on jsp page or servlet page?

I want to display an image located on my local drive. I use the sun java 8 application server. For example, if I create the abc.jpg file dynamically and save it in c: \ abc.jpg, then how can I use it in jsp or servlets? How to display it on jsp or servlet pages? I know that the c: \ abc.jpg encoding path for displaying the image does not work, because it is not in the web server.

+3
source share
2 answers

Basically, just create Servletone that receives InputStreamfrom it with the help FileInputStreamand writes it to OutputStreamin HttpServletResponsetogether with the correct set of response headers, at least with content-type. Finally, call this servlet in the srcelement attribute <img>along with the file identifier as a request parameter or pathinfo. For instance:.

File file = new File("c:/abc.jpg");

response.setContentType(getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(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) {}
}

Here you can find the complete basic example: http://balusc.blogspot.com/2007/04/imageservlet.html

+4
source

Maybe everyone did not understand the question.

If the images are located on your local drive and you want your web server to serve them all over the world, then as a first step you need to upload them to your web server.

URL- <img>, .

+2

Source: https://habr.com/ru/post/1727250/


All Articles