Search Posts

How to display images uploaded using getServletContext().getRealPath("/") on JSP page?

I have a jsp page which uploads images on to the root of the project. But I cannot see those images on the project explorer in Netbeans IDE. But i can see the folder in C:UsersGireesh PaiDocumentsNetBeansProjectsmatrimonial_2buildwebimages
and the files are correctly getting uploaded too.
But I’m unable to display it on a jsp page by providing a link to it. Can any one help me out ?
I’m attaching the code for upload below.

try
    {
        //uploadfile = config.getServletContext().getRealPath("/") + "images/";
        uploadfile = config.getServletContext().getRealPath("/") + "images/";
        System.out.println(uploadfile);
        File uploaddir = new File(uploadfile);
        if (!uploaddir.exists()) //TO CHECK WHETHER THE DIR EXISTS OR NOT
        {
            uploaddir.mkdir();  //IF NOT CREATE A NEW ONE
        }
        Iterator itr = items.iterator();
        while (itr.hasNext())
        {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField())
            {

            }
            else
            {
                itemName = new File(item.getName()).getName();
                File savedFile = new File(uploadfile + itemName);
                item.write(savedFile);
                String fpath=itemName;

                DataBase_handler.executeUpdate("INSERT INTO matrimonialdb.image_path_test (name,image_path) VALUES ('"+name+"','"+fpath+"')");
            }
            out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath("/")+"uploadedFiles"+""+itemName+"</td></tr>");
        }
    }

This is the code i tried to display the uploaded image in jsp.

<table>
        <%
            String photo="";
            String path="";
            String name="";
            ResultSet rs = DataBase_handler.executeQuery("SELECT * FROM matrimonialdb.image_path_test WHERE id='"+1+"'");
            while(rs.next())
            {
        %>
        <tr>
            <td>Name : </td>
            <td><%= rs.getString("name") %></td>
        </tr>
        <tr>
            <%= photo = rs.getString("image_path")%>
            <% 

                path="C:UsersGireesh PaiDocumentsNetBeansProjectsmatrimonial_2buildwebimages"+photo;


                //out.println("Path = "+path);
            %>
            <td><img src="path" alt=""/></td>
            <td><!--<img src="images/21586795_735270243332705_7358388165873699009_o.jpg" alt=""/>--></td>
        </tr>
        <%
            }
        %>
    </table>

Source: Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *