Saving Image in Folder and path in database using Java

Here is the code to get the image from the user and store it in a folder and store the image path in Database.

JSP and Servlet
MySql Database
Tested with Netbeans 8.0

Database – create table with name and photourl as fields with datatype varchar().

JSP: (Upload Image)

<form action="UploadServlet" method="post" enctype="multipart/form-data"> <br><br>
<table>
      <tr>
                 <td>UserName:  </td>
                 <td width='10px'></td>
                 <td><input type="text" name="unname"/></td>
      </tr>
      
      <tr>
                 <td>Upload: </td>
                 <td width='10px'></td>
                 <td><input type="file" name="filecover" value="Upload"/></td>
      </tr>
      <tr>
          <td><input type="submit" value="submit"></td>
      </tr>
</table>
</form>

Servlet:

@MultipartConfig(fileSizeThreshold=1024*1024*2, 
maxFileSize=1024*1024*10, 
maxRequestSize=1024*1024*50)
 
public class UploadServlet extends HttpServlet {
private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
        }
    }
    return null;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out1 = response.getWriter()) {
            HttpSession session=request.getSession();
            String name=request.getParameter("unname");
            Part filePart = request.getPart("filecover");
            
          
          String photo="";
          String path="path here";
          
          File file=new File(path);
          file.mkdir();
          String fileName = getFileName(filePart);
          
          OutputStream out = null;
          
            InputStream filecontent = null;
            
            PrintWriter writer = response.getWriter();
            try {
        out = new FileOutputStream(new File(path + File.separator
                + fileName));
        
        filecontent = filePart.getInputStream();
     
 
        int read = 0;
        final byte[] bytes = new byte[1024];
 
        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
           
            photo=path+"/"+fileName;
            
            
        }
        
       
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
        Statement stmt=con.createStatement();
       
        stmt.executeUpdate("insert into name(Name,photourl) values('"+name+"','"+photo+"')"); 
       
     }
     catch(Exception e)
     {
         
     }
     out1.println ("<html><body><script>alert('Sucessfully Saved! Check the database and the path!');</script></body></html>");
}
}

 

 

18 thoughts on “Saving Image in Folder and path in database using Java”
  1. Sir I have used your code as mentioned above but at the time of retrieving image it wont display image on my jsp page….so please give me the solution….
    here is my code for retrieving the image:

    /*retrive.jsp */

    Insert title here

    <img src="” width=”300″ height=”300″ />

  2. thanks sir it’s working
    but only one confusion which folder image saved
    means where is folder location of image

Leave a Reply

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