Tuesday, May 21, 2013

How to Upload Image using JSP,Servlet and MySql Database


Create database and table

Paste the jars file in WebRoot->WEB-INF->lib folder.


Jar required:- 

commons-fileupload.jar


Write the following code in jsp:--

FileUpload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<body>
    <h1>File Upload Form</h1>
    <fieldset>
        <legend>Upload File</legend>
               <span class="fielderror">${messages.image}</span><br>
        <form action="fileuploadexample" method="post" enctype="multipart/form-data">
            <label for="fileName">Select File: </label>
            <input id="fileName" type="file" name="fileName" size="30"/><br/>           
            <input type="submit" value="Upload"/>
        </form>
    </fieldset>
</body>
</html>


Write the following code in Servlet:--


package com;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadExample extends HttpServlet{
      
       private static final long serialVersionUID = 1L;

       protected void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
                
           Map<String, String> messages = new HashMap<String, String>();
           request.setAttribute("messages", messages);
               
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        
           if (isMultipart) {
             // Create a factory for disk-based file items
             FileItemFactory factory = new DiskFileItemFactory();

             // Create a new file upload handler
             ServletFileUpload upload = new ServletFileUpload(factory);
        
            try {
              
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                FileItem imageFile = (FileItem) iterator.next();
                if(imageFile.getSize() > 100000){
                messages.put("image", "Image size more than 50kb not allowed");
                request.getRequestDispatcher("FileUpload.jsp").forward(request, response);
                return ;
                }
              if (!imageFile.isFormField()) {
                String fileName = imageFile.getName();      
                String fileBase = getServletContext().getInitParameter("IMAGE_FILEBASE");
                File filePath  = new File(fileBase  + File.separator);
                              
                if (!filePath.exists()) {
                    boolean status = filePath.mkdirs();
                   }
                         
               File uploadedFile = new File(filePath + "/" + fileName);
               imageFile.write(uploadedFile);
               // Save the below path in database
 System.out.println(  "Save Path in Database: "+getServletContext().getInitParameter("imgsd") + "images/" + fileName);
                           
                     }
                  }
                } catch (FileUploadException e) {
                       e.printStackTrace();
                } catch (Exception e) {
                       e.printStackTrace();
                 }
            }
              
             response.sendRedirect("Success.jsp");
       }      
}



Web.xml file


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
       xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>  
 
  <servlet>
              <servlet-name>FileUpload</servlet-name>
              <servlet-class>com.FileUploadExample</servlet-class>
       </servlet>
       <servlet-mapping>
              <servlet-name>FileUpload</servlet-name>
              <url-pattern>/fileuploadexample</url-pattern>
       </servlet-mapping>
      
       <context-param>
              <param-name>IMAGE_FILEBASE</param-name>
              <param-value>
C:/Test_Workspace/FileUploadExample/WebRoot/images/</param-value>
       </context-param>          
       <context-param>
              <param-name>imgsd</param-name>
              <param-value>http://localhost:8080/</param-value>
       </context-param>
      
  <welcome-file-list>
    <welcome-file>FileUpload.jsp</welcome-file>
  </welcome-file-list>
</web-app>


Second Example:


When Input TYPE TEXT Value from JSP form (enctype=“multipart/form-data”)

In brandimageupload.jsp, write

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page import="com.bean.*"%>
<%@page import="com.dao.*"%>
<%@page import="java.util.*"%>
<title>Upload Images</title>
<content tag="heading">Upload Images</content>
<body >
<%          
                BrandDAO brandDao = new BrandDAO();
                 List<Brand> brandList = brandDao.getBrand();
                         request.setAttribute("brandList", brandList);
 %>
<div class="main">
 <c:if test="${messages.upload !=null}">
       <div class="rounded_colhead message">${messages.upload}</div>
   </c:if>
    <form id="imageUploadForm" action="UploadBrandImage" method="post" enctype="multipart/form-data">
                       
                        <fieldset>
           <div class="form_row">
                                    <label >Brand</label>
                    <select id="selectDealBrandFieldId" name="selectDealBrandField">
                        <option value="0">Select</option>                                       
                             <c:forEach  var="brandList" items="${brandList}">                                
                                     <option value="${brandList.id}">${brandList.brandName}</option>                                                   
                              </c:forEach>        
                        </select>
               </div>    
                          
            <div class="form_row">
                        <label >Image Name</label>
                        <input type="text" class="text" name="nameField" id="nameId"/>
            </div>
          
            <div class="form_row">
                                    <label>Image File :</label>
                <input type="file"  name="fileName" displayName="File"/>
            </div>
                        <div class="form_row">
                        <label></label>
            <input type="submit" class="button" value="Upload"  onclick="return validateData()"/>
                            </div>
        </fieldset>         
            </form>  
 </div>
           
           
<script type="text/javascript">
function validateData() {
if(document.getElementById("selectDealBrandFieldId").value.trim() == "0"){
    alert("Select Brand Name");
    return false;
 }
if(document.getElementById("nameId").value.trim() == ""){
    alert("Image Name is required");
    return false;
 }
      return true;

}
</script>                    
</body>

Servlet

package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bean.BrandImage;
import com.dao.BrandImageDAO;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadBrandImage extends HttpServlet {
           
           
            private static final long serialVersionUID = 1L;

            public void doGet(HttpServletRequest req, HttpServletResponse resp)
                                    throws ServletException, IOException {
                        performTask(req, resp);
            }

            public void doPost(HttpServletRequest req, HttpServletResponse resp)
                                    throws ServletException, IOException {
                        performTask(req, resp);
            }

            private void performTask(HttpServletRequest req, HttpServletResponse resp)
                                    throws ServletException, IOException {                      
                       
                         Map<String, String> messages = new HashMap<String, String>();
                         req.setAttribute("messages", messages);
                        BrandImage brandImage = new BrandImage();
                        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
       
        if (isMultipart) {
                       
          // Create a factory for disk-based file items
          FileItemFactory factory = new DiskFileItemFactory();

          // Create a new file upload handler
          ServletFileUpload upload = new ServletFileUpload(factory);
    
         try {
          
             List items = upload.parseRequest(req);
             Iterator iterator = items.iterator();
             while (iterator.hasNext()) {
             FileItem item = (FileItem) iterator.next();
            
             if (item.isFormField()) { 
                 //Plain request parameters will come here. 
               String fieldName = item.getFieldName(); 
               String value = item.getString();
              
               if(fieldName.equals("selectDealBrandField")){
                           brandImage.setBrandType(value);
               }
               if(fieldName.equals("nameField")){
                           brandImage.setImageName(value);
               }
              
             }
            
            // if(item.getSize() > 100000){
             //messages.put("image", "Image size more than 50kb not allowed");
            // request.getRequestDispatcher("brandimageupload.jsp").forward(req, resp);
           //  return ;
           //  }
           if (!item.isFormField()) {
             String fileName = item.getName();  
             if( fileName.isEmpty()){
                          req.getRequestDispatcher("/pages/brandimageupload.jsp").forward(req, resp);
                         return;
               }
             String fileBase = getServletContext().getInitParameter("BRAND_FILEBASE");
             File filePath  = new File(fileBase  + File.separator);
                          
          
            File uploadedFile = new File(filePath + "/" + fileName);
            item.write(uploadedFile);
           
            // Save the below path in database
            String url = getServletContext().getInitParameter("BRAND_URLBASE") + fileName ;
             System.out.println("url:" +url );
                             brandImage.setUrl(url);
                             BrandImageDAO imgDao = new BrandImageDAO();
                             imgDao.addBrandImage(brandImage);
                             messages.put("upload","Brand Images uploaded successfully");
                             req.getRequestDispatcher("/pages/brandimageupload.jsp").forward(req, resp);
                  }
               }
             } catch (FileUploadException e) {
                    e.printStackTrace();
             } catch (Exception e) {
                    e.printStackTrace();
              }
         }
      
                         
            }


}

Web.xml

<servlet>
       <servlet-name>UploadBrandImage</servlet-name>
       <servlet-class>com.servlet.UploadBrandImage</servlet-class>
 </servlet>
 
   <servlet-mapping>
              <servlet-name>UploadBrandImage</servlet-name>
              <url-pattern>/pages/UploadBrandImage</url-pattern>
       </servlet-mapping>
      
<!-- Brand Image upload path -->
       <context-param>
              <param-name>BRAND_FILEBASE</param-name>
              <param-value>C:/Test_Workspace/test/WebRoot/img/brands/</param-value>
       </context-param>
       <context-param>
              <param-name>BRAND_URLBASE</param-name>
              <param-value>http://localhost:8080/img/brands/</param-value>
       </context-param>
<!-- Brand Image upload path End-->

DAO class

package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.bean.BrandImage;
import com.common.ApplicationException;
import com.common.DBUtil;

public class BrandImageDAO {
           
            public int addBrandImage(BrandImage img) throws ApplicationException {
                       
                         Connection connection = null;
                         PreparedStatement preparedStatement=null;
                         int row = 0;               
                                                 
 String sql_query = "insert into dd_brand_image(brand_id, image_name, url) values( ? , ? , ? )";
                                                                      
                                    try {
                                               
                         connection = DBUtil.getConnection();
                        preparedStatement = connection.prepareStatement(sql_query);
                        preparedStatement.setString(1, img.getBrandType());
                        preparedStatement.setString(2, img.getImageName());
                        preparedStatement.setString(3, img.getUrl());
                        row=preparedStatement.executeUpdate();

                        } catch (SQLException e) {
                                     ApplicationException exception = new ApplicationException(
                                "Unable to insert data: " + e.getMessage(), e);
                        throw exception;
                        }finally{
                                    DBUtil.closeResource(connection, preparedStatement, null);
                        }
                                     return row;   
            }
           
                       
           
}

Where table as:--

CREATE TABLE `dd_brand_image` (                                                    
                  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,                              
                  `brand_id` mediumint(8) unsigned NOT NULL,                                        
                  `image_name` varchar(255) NOT NULL,                                              
                  `url` varchar(255) DEFAULT NULL,                                                 
                  PRIMARY KEY (`id`),                                                              
                  KEY `fk_brandimage` (`brand_id`),                                                
           CONSTRAINT `fk_brandimage` FOREIGN KEY (`brand_id`) REFERENCES `dd_brand` (`id`) 
                ) ENGINE=InnoDB  DEFAULT CHARSET=latin1