Abhijit Kumbhar
Abhijit Kumbhar

Reputation: 961

How to display image using <img src=" "> from system directory in JSP

I am trying to fetch image which is stored in My local system directory, I stored image path in MySQl database and the path of image is

 H:\IVS-FEB 2016\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\IVS\uploads\share1.png

I'm trying to fetch this path using

<img src="<%String pathup =rs2.getString("pathup");out.print(pathup);%>" width="200" height="200" alt="Uploaded by user">

But this will not displaying image on my webpage? :( I got following error when I hit inspect element option in browser

Not allowed to load local resource: file:///H:/IVS-FEB%202016/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/IVS/uploads/share1.png

Upvotes: 1

Views: 1915

Answers (1)

Arun Xavier
Arun Xavier

Reputation: 771

Write a Java Servlet. See example tutorial.

Eg:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    ServletOutputStream oStream;
    String fileName = "your file";
    try (FileInputStream iStream = new FileInputStream(new File(fileName))) 
    {
        response.setContentType("image/png");
        oStream = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int len;
        while ((len = iStream.read(buffer)) != -1) 
        { oStream.write(buffer, 0, len); }

    }

    oStream.flush();
    oStream.close();
}

Then in your HTML/JSP page use:

<img src="ImageServlet"/>

You can pass parameters if you have multiple images based on any condition and do your logic to choose in the Servlet class.

Upvotes: 2

Related Questions