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)

This is page for user's input as well as output.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
 <%@ taglib uri="/struts-tags" prefix="s"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">  
 <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>  
 <body bgcolor="green">  
 <s:form id="uploadjdbc" name="uploadjdbc" theme="simple" method="POST" enctype="multipart/form-data">  
      <table width="75%" align="center" border="1">  
                <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><td colspan="6">&nbsp;</td></tr>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                     <s:file id="upload_1" name="upload_1" label="File" onblur="javascript: validateFileName();" />  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                     <s:file id="upload_2" name="upload_2" label="File" onblur="javascript: validateFileName();" />  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                     <s:file id="upload_3" name="upload_3" label="File" onblur="javascript: validateFileName();" />  
           <tr><td colspan="6">&nbsp;</td></tr>  
                <td colspan="6" align="center">  
                     <input type="button" id="btnUpload" value="Upload">&nbsp;&nbsp;  
                     <input type="reset" id="btnReset" value="Reset">  
 <script type="text/javascript">  

This file contains information about which action class need to be invoked.
 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "">  
      <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="">  
                <result name="success">jsp/file_upload.jsp</result>  
                <result name="input">jsp/error.jsp</result>  
                <result name="error">jsp/error.jsp</result>  
           <action name="getimage" class="" method="invoke" />  
This invoke() function will be called by struts.xml for displaying already uploaded images. It writes the byte array data to the output Stream.
 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();  
      public String getId() {  
           return id;  
      public void setId(String id) {  
  = id;  
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.
 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  
                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) {  
                flag = false;  
           } finally {  
                try {  
                } catch (SQLException e) { }  
           return flag;  
      public byte[] getFileBlob(File file) {  
           byte[] bFile = new byte[(int) file.length()];  
           try {  
                FileInputStream fileInputStream = new FileInputStream(file);  
           } catch (Exception e) {  
           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 {  
                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 ( {  
                     imageInByte = rs.getBytes(1);  
           } catch (Exception e) {  
           return imageInByte;  

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';  

 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi=""  
      xmlns="" xmlns:web=""  
      id="WebApp_ID" version="3.0">  

Download Full Code with Jars

+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