Thursday 14 March 2013

Upload a file/image in Folder using Servlet

This Post shows how to implement a Java web application that uploads files to server and save the files into folders and save it's path into database.

Steps you need to follow
1. Create a Mysql database table.
2. Create a upload form page.
3. Create a folder in your 'C' drive named images;
4. Create a File upload Servlet.

Query for create a database table :

create database UploadFile;
use UploadFile;
CREATE TABLE customerDetail(
'contact_id' int(11) not null auto_increment,
'first_name' varchar(50) not null,
'last_name' varchar(50) not null,
'file' varchar(200) not null,
primary key(contact_id)
);


'photo' is varchar type because I am storing path of the file in this field, if you want to insert whole file in mysql database then you need to set type of  'file' to 'blob'. In this example i am not using blob because it may be cause of image distortion or a little bit hard to implement, in blob field firstly we need to covert file into bytes and then store in mysql.

Coding for uploadform.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
      <title>Image Upload</title>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
    <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
    <table width="400px" align="center" border=0>
       <tr>
           <td align="center" colspan=2>
            Image Details</td>
       </tr>
       <tr>
           <td>First Name </td>
           <td>
               <input type="text" name="firstname">
           </td>
       </tr>
       <tr>
           <td>Last Name </td>
           <td>
               <input type="text" name="lastname">
           </td>
       </tr>
       <tr>
           <td>Image Link: </td>
           <td>
               <input type="file" name="file">
           </td>
       </tr>
       <tr>
           <td></td>
           <td>
              <input type="submit" name="submit" value="Submit"></td>
       </tr>
   </table>
</form>
</body>
</html>

You need to set enctype of form tag to "multipart/form-data" it tells that form contain multipart data.
This page contain two text fields for first name and last name and one file type field for files, after submitting the form data send to FileUploadServlet servlet where all other processing is to be done.

 Coding for FileUploadServlet.java:


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
                 maxFileSize=1024*1024*10,      // 10MB
                 maxRequestSize=1024*1024*50)

public class FileUploadServlet extends HttpServlet {
    private static final String SAVE_DIR="images";
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
            String savePath = "C:" + File.separator + SAVE_DIR;
                File fileSaveDir=new File(savePath);
                if(!fileSaveDir.exists()){
                    fileSaveDir.mkdir();
                }
            String firstName=request.getParameter("firstname");
            String lastName=request.getParameter("lastname");
            Part part=request.getPart("file");
            String fileName=extractFileName(part);
            /*if you may have more than one files with same name then you can calculate some random characters and append that characters in fileName so that it will  make your each image name identical.*/
            part.write(savePath + File.separator + fileName);
           /* 
            //You need this loop if you submitted more than one file
            for (Part part : request.getParts()) {
            String fileName = extractFileName(part);
            part.write(savePath + File.separator + fileName);
        }*/
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/UploadFile","root","root");
            String query="INSERT INTO customerDetail (first_name, last_name, file) values (?, ?, ?)";
           
                PreparedStatement pst;
                pst=con.prepareStatement(query);
                pst.setString(1, firstName);
                pst.setString(2,lastName);
                String filePath= savePath + File.separator + fileName ;
                pst.setString(3,filePath);
                pst.executeUpdate();
    }
    // file name of the upload file is included in content-disposition header like this:
    //form-data; name="dataFile"; filename="PHOTO.JPG"
    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length()-1);
            }
        }
        return "";
    }
}


In this servlet, we use two annotations:
          @WebServlet: marks this servlet so that the servlet container will load it at startup, and map it   to the URL pattern /FileUploadServlet.
          @MultipartConfig: indicates this servlet will handle multipart request. We restrict maximum size of the upload file up to 16 MB.


Now your file is successfully uploaded in your folder and the path is stored in mysql.
Go in c drive and check it out and check for entry in mysql fire a query(select * from customerDetail) on mysql.

4 comments:

  1. Hallo Jalesigh, thank you so much for sharing this code. Did not work at first but after just a little twick it worked perfectly. I think the images in the folder should have special id's in order not to call the wrong image for display. Can the url be called in jsp or html?

    Thanks for the good work.

    ReplyDelete
    Replies
    1. Hi Andy, we can rename the image by product_title+price+image_name. it will remove duplicate names almost and call to right images.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Tipeco Taps - Titanium Dioxide - TITanium Oil Shave
    Tipeco Taps Taps is a highly effective does titanium set off metal detectors sunscreen that gives the skin to men\'s titanium wedding bands grow price of titanium and retain the babyliss pro titanium essential titanium gravel bike amino acids.

    ReplyDelete