Saturday, December 28, 2013

How to upload Multiple Files- Images (blob data) with enctype="multipart/form-data" in Oracle Database using Struts2, JDBC and Eclipse IDE

In this tutorial we are working with multiple images (blob data type) uploading with other two values as file id and name (these two values are not entered by user as input in database table). And every time we are replacing new values with previous stored values(here we are working with three user inputs as browse button or uploader).

 
Here we are using enctype="multipart/form-data", Struts2 jars and tags, Apache Tomcat 7.0 and Java 6 (but you can use them as other versions too, available on your system).
you can also Download full code with required Jars. 
Download Full Code with Jars 

Project View in Project Explorer

Create a table with name FILES and here we are using TEST Schema(but you can use others too for example HR Schema)
FILES Table

file_upload.jsp
This is page for user's input as well as output.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <%@ taglib uri="/struts-tags" prefix="s"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <script type="text/javascript" src="js/jquery-1.7.2.js"></script>  
 <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>  
 <title>FILE UPLOAD</title>  
 </head>  
 <body bgcolor="green">  
 <s:form id="uploadjdbc" name="uploadjdbc" theme="simple" method="POST" enctype="multipart/form-data">  
      <table width="75%" align="center" border="1">  
           <tr>  
                <td width="33%" colspan="2" align="center" ><img src="<s:url action='getimage?id=image_1' />" id="imgLogin_1" name="imgLogin_1" width="400" /></td>  
                <td width="34%" colspan="2" align="center" ><img src="<s:url action='getimage?id=image_2' />" id="imgLogin_2" name="imgLogin_2" width="400" /></td>  
                <td width="33%" colspan="2" align="center" ><img src="<s:url action='getimage?id=image_3' />" id="imgLogin_3" name="imgLogin_3" width="400" /></td>  
           </tr>  
           <tr><td colspan="6">&nbsp;</td></tr>  
           <tr>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                </td>  
                <td>  
                     <s:file id="upload_1" name="upload_1" label="File" onblur="javascript: validateFileName();" />  
                </td>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                </td>  
                <td>  
                     <s:file id="upload_2" name="upload_2" label="File" onblur="javascript: validateFileName();" />  
                </td>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                </td>  
                <td>  
                     <s:file id="upload_3" name="upload_3" label="File" onblur="javascript: validateFileName();" />  
                </td>  
           </tr>  
           <tr><td colspan="6">&nbsp;</td></tr>  
           <tr>  
                <td colspan="6" align="center">  
                     <input type="button" id="btnUpload" value="Upload">&nbsp;&nbsp;  
                     <input type="reset" id="btnReset" value="Reset">  
                </td>  
           </tr>  
      </table>  
 </s:form>  
 </body>  
 <script type="text/javascript">  
      $.getScript('js/file_upload.js');  
 </script>  
 </html>  

struts.xml
This file contains information about which action class need to be invoked.
 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">  
 <struts>  
      <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
      <constant name="struts.devMode" value="false" />  
      <constant name="struts.custom.i18n.resources" value="ApplicationResources" />  
      <constant name="struts.ui.templateDir" value="template" />  
      <constant name="struts.multipart.maxSize" value="5242880" />  
      <package name="uploadjdbc" extends="struts-default">  
           <action name="upload" class="blog.webideaworld.com.FileUpload">  
                <result name="success">jsp/file_upload.jsp</result>  
                <result name="input">jsp/error.jsp</result>  
                <result name="error">jsp/error.jsp</result>  
           </action>  
           <action name="getimage" class="blog.webideaworld.com.FileUpload" method="invoke" />  
      </package>  
 </struts>  

FileUpload.java
This invoke() function will be called by struts.xml for displaying already uploaded images. It writes the byte array data to the output Stream.
 package blog.webideaworld.com;  
 import javax.servlet.http.HttpServletResponse;  
 import org.apache.struts2.ServletActionContext;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class FileUpload extends ActionSupport {  
      private static final long serialVersionUID = 1L;  
      private FileUploadHelper helper = new FileUploadHelper();  
      private String id = "";  
      public String execute() {  
           if (helper.saveFiles()) {  
                return SUCCESS;  
           } else {  
                return ERROR;  
           }  
      }  
       
      public void invoke() throws Exception {  
           HttpServletResponse response = ServletActionContext.getResponse();  
           response.getOutputStream().write(helper.getFiles(id));  
           response.getOutputStream().flush();  
      }  
      public String getId() {  
           return id;  
      }  
      public void setId(String id) {  
           this.id = id;  
      }  
 }  

FileUploadHelper.java
setFileMap() is setting all the files received from JSP to a map. "mapFile.get("upload_"+i)" is getting one file from map. "getFileBlob(oFile)" is reading file from the input stream. and some other required explanation is inside code.
 package blog.webideaworld.com;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
 import java.util.Enumeration;  
 import java.util.HashMap;  
 import java.util.Map;  
 import org.apache.struts2.ServletActionContext;  
 import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;  
 public class FileUploadHelper {  
      Map<String, File> mapFile = new HashMap<String, File>();  
      byte[] imageInByte = null;  
      public boolean saveFiles() {  
           Connection conn = null;  
           PreparedStatement pstmt = null;  
           Integer intRowsAffected = 0;  
           boolean flag = true;  
           byte[] bData = null;  
           File oFile = null;  
           try {  
                setFileMap();                    //Setting all the files received from JSP to a map  
                //Database connectivity  
                Class.forName("oracle.jdbc.OracleDriver");  
                conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "test", "test");  
                for (int i = 1; i <= 3; i++) {  
                     intRowsAffected = 0;  
                     oFile = mapFile.get("upload_"+i);               //Getting one file from map  
                     if (oFile != null) {  
                          bData = getFileBlob(oFile);                    //Reading file from the input stream  
                          //If file with id (i) already exists, then it is updated  
                          pstmt = conn.prepareStatement("UPDATE FILES SET FILE_DATA=? WHERE FILE_ID=?");  
                          pstmt.setBytes(1, bData);  
                          pstmt.setInt(2, i);  
                          intRowsAffected = pstmt.executeUpdate();  
                          if (intRowsAffected == 0) {               //If file does not exists, a new entry is inserted  
                               pstmt = conn.prepareStatement("INSERT INTO FILES (FILE_ID, FILE_NAME, FILE_DATA) VALUES (?,?,?)");  
                               pstmt.setInt(1, i);  
                               pstmt.setString(2, oFile.getName());  
                               pstmt.setBytes(3, bData);  
                               intRowsAffected = pstmt.executeUpdate();  
                               if (intRowsAffected == 0) {          // If insertion fails, error page will be displayed  
                                    return false;  
                               }  
                          }  
                     }  
                }  
           } catch (Exception e) {  
                System.out.println(e);  
                flag = false;  
           } finally {  
                try {  
                     pstmt.close();  
                     conn.close();  
                } catch (SQLException e) { }  
           }  
           return flag;  
      }  
      public byte[] getFileBlob(File file) {  
           byte[] bFile = new byte[(int) file.length()];  
           try {  
                FileInputStream fileInputStream = new FileInputStream(file);  
                fileInputStream.read(bFile);  
                fileInputStream.close();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           return bFile;  
      }  
      private void setFileMap() {  
           MultiPartRequestWrapper mprw = (MultiPartRequestWrapper) ServletActionContext.getRequest();  
           Enumeration<String> e = mprw.getFileParameterNames();  
           while(e.hasMoreElements()) {  
                String str = e.nextElement();          //this will give the id from the JSP  
                mapFile.put(str, mprw.getFiles(str)[0]);  
           }  
      }  
      /**  
       * @param id  
       * @return byte array corresponding to the id.  
       */  
      public byte[] getFiles(String id) {  
           Connection conn = null;  
           Statement stmt = null;  
           ResultSet rs = null;  
           try {  
                Class.forName("oracle.jdbc.OracleDriver");  
                conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "test", "test");  
                stmt = conn.createStatement();  
                rs = stmt.executeQuery("SELECT FILE_DATA FROM FILES WHERE FILE_ID="+Integer.parseInt(id.split("_")[1]));  
                if (rs.next()) {  
                     imageInByte = rs.getBytes(1);  
                }  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
           return imageInByte;  
      }  
 }  

file_upload.js
This is for validation part.
 $('#btnUpload').click(function () {  
      if ($('#upload_1').val() == '' && $('#upload_2').val() == '' && $('#upload_3').val() == '') {  
           alert('Select atleast 1 Image !!!');  
           return false;  
      }  
      document.forms[0].action = 'upload.action';  
      document.forms[0].submit();  
 });  

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
      id="WebApp_ID" version="3.0">  
      <display-name>uploadjdbc</display-name>  
      <welcome-file-list>  
           <welcome-file>jsp/file_upload.jsp</welcome-file>  
      </welcome-file-list>  
      <filter>  
           <filter-name>struts2</filter-name>  
           <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
      </filter>  
      <filter-mapping>  
           <filter-name>struts2</filter-name>  
           <url-pattern>/*</url-pattern>  
      </filter-mapping>  
 </web-app>  

Download Full Code with Jars

output:
+Sarthak Goel 

Also Read How to use Struts2 Iterator tag to get Users Details from List with Oracle 10g XE and Eclipse

No comments:

Popular Posts