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" "">
      <title>Image Upload</title>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
    <table width="400px" align="center" border=0>
           <td align="center" colspan=2>
            Image Details</td>
           <td>First Name </td>
               <input type="text" name="firstname">
           <td>Last Name </td>
               <input type="text" name="lastname">
           <td>Image Link: </td>
               <input type="file" name="file">
              <input type="submit" name="submit" value="Submit"></td>

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

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;

@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
                 maxFileSize=1024*1024*10,      // 10MB

public class FileUploadServlet extends HttpServlet {
    private static final String SAVE_DIR="images";
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {
        PrintWriter out = response.getWriter();
            String savePath = "C:" + File.separator + SAVE_DIR;
                File fileSaveDir=new File(savePath);
            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);
            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.setString(1, firstName);
                String filePath= savePath + File.separator + fileName ;
    // 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.