You are here: Home // Programming // File upload to BLOB field and display attachment dialog box

File upload to BLOB field and display attachment dialog box

Sometimes a developer needs to provide the feature in their web application to upload file. This file can be anything like documents (PDF, doc, rtf etc.) or image (jpg, bmp, tif, gif etc.) or zip file. And after uploading the developer needs to provide another feature to download the file by clicking a link.


There can numerous ways to provide this functionality in a web application. I’m going to discuss about the database approach for doing so. In the database approach, the RDBMs should have the BLOB feature enabled to store the uploaded file as an image inside it.

 The tools that would be used in this tutorial are Oracle database, Struts. In Oracle we’ve BLOB type of field which can store large size files. Now first thing we’ll code in the JSP side.

 In the jsp the file upload field can be achieved by using

<html:file property=”fieldname” name=”formname” styleClass=”abcd”/>

element. This element is the struts HTML element. The property attribute corresponds to the fieldname in the formbean (Java formbean in struts framework) and name corresponds to the formbean name given in the struts framework. Also, the encType in the should be “multipart/form-data”. A sample jsp code is given below:

 fileupload.jsp-

 

 DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>

<html:html>

<HEAD>

<METAhttp-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>

<METAname=”GENERATOR” content=”IBM WebSphere Studio”>

<TITLE>TITLE>

HEAD>

<BODY>

<html:form name=”uploadForm” enctype=”multipart/form-data” action=”/uploadFile” type=”com.cts.testfileupload.formbean.UploadForm”>

      <html:file name=”uploadForm” size=”25″ property=”document” />

      <html:submit value=”Submit” />

html:form>

BODY>

html:html>

 

  The sample code for UploadForm.java bean is given below-

 

package com.tctalk.testfileupload.formbean;import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.upload.FormFile;

 

/**

 * Form bean for a Struts application.

 */

public class UploadForm extends ActionForm {

      private FormFile document;

      private String depPerfFileName;

 

      public String getDepPerfFileName() {

            return depPerfFileName;

      }

 

      public FormFile getDocument() {

            return document;

      }

      public void setDepPerfFileName(String string) {

            depPerfFileName = string;

      }

       public void setDocument(FormFile file) {

            document = file;

      }

 

}

 

 

The document is the field that corresponds to the file upload field in the Jsp. Note that the type of it should strictly be Apache FormFile(org.apache.struts.upload.FormFile).

 

  

This comes with struts packages by default so you don’t need to add any jar library here.

 

Also the corresponding entry in the Struts config is given as-

 

      <form-beans>            <form-bean name=”uploadForm” type=”com.cts.testfileupload.formbean.UploadForm”>

            form-bean>

      form-beans>

 

Now in the action we got the FormFile object. This object holds the uploaded file and also can provide information regarding this uploaded file. E.g. is-

UploadForm uploadForm = (UploadForm) form;String newName    = “”;

int fileSize = 0;

 

//retrieving uploaded file information

 System.out.println(”Uploaded file name::” + uploadForm.getDocument().getFileName());

 

System.out.println(”Uploaded file size::” + uploadForm.getDocument().getFileSize());

 

System.out.println(”Uploaded file content type::” + uploadForm.getDocument().getContentType());

 

newName = uploadForm.getDocument().getFileName();

fileSize = uploadForm.getDocument().getFileSize();

InputStream inFile = uploadForm.getDocument().getInputStream();

 

The statement

InputStream inFile = uploadForm.getDocument().getInputStream(); converts the uploaded file in the InputStream object which will then be used in the DAO layer( layer which interact with database) to store in the database.

 

 UploadFileDAO.uploadFileToBLOB(inFile, fileSize, newName);

 

 

 

 

Below I’ll provide a sample JDBC code (uploadFileToBLOB()) which stores the entire file stream in the database along with file name and other information.

 

public static boolean uploadFileToBLOB(InputStream iStream, int fileSize, String fileName){            boolean execStatus = false;

            Connection dbConnection = null;

            PreparedStatement pstmt = null;

            ResultSet rset = null;

           

            try {

                  //get the datasource to coonect to Oracle DB

                  dataSource = lookUp(JNDI_NAME);

                  //get the connection

                  dbConnection = dataSource.getConnection();

                  //private static final String INSERT_QRY =

// “INSERT INTO XXX.DOC_TBL(DOC_ID,DOC_NME,DOC) VALUES(?,?,?)”;

//Here DOC is BLOB type to store the entire file, DOC_ID is the unique

//id for each row and DOC_NME holds the document name

                  pstmt = dbConnection.prepareStatement(INSERT_QRY);

// get a prepared statement object

                  pstmt.setInt(1,getDocId(dbConnection));//set docid

                  pstmt.setString(2,fileName);//set the filename

                  pstmt.setBinaryStream(3,iStream,fileSize);

//set the uploaded file stream object

                  rset = pstmt.executeQuery();//execute the query

                  System.out.println(”Insertion successfull”);

            } catch (SQLException sqe) {

                  sqe.printStackTrace();

            } catch (Exception e) {

                  e.printStackTrace();

            } finally{

                  try{

                        rset.close();

                        dbConnection.close();

                  } catch (SQLException sqe) {

                        sqe.printStackTrace();

                  }

            }

            return execStatus;

      }

 

Now the database update part is done and our uploaded file is now inside the database. The next step that we need to do is to display a link to the user which will point to a servlet. This servlet takes only one argument- The DOC_ID. Based on the DOC_ID it fetches the data from database and flushes the binary stream object to client browser. Browser display a “Save As” attachment dialog box to the user, user can save the file to either hard disk or can open in a temporary section to view the file.

 

First I’ll provide the sample code for the servlet which is responsible to fetch the data from database and display the “Save As” attachment dialog box to the user. It uses the UploadFileDAO.getDocDownload function in the DAO layer to get the data from database.

 

Servlet code-

package com.tctalk.testfileupload.servlets;import java.io.FileOutputStream;

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import com.tctalk.testfileupload.dao.UploadFileDAO;

import com.tctalk.testfileupload.vo.FileVO;

 

public class DownLoadServlet extends HttpServlet {

 

public void doGet(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

            try {

                  processDownload(req, resp);

            } catch (Exception e) {

                  e.printStackTrace();

            }

      }

 

      public void doPost(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

            try {

                  processDownload(req, resp);

            } catch (Exception e) {

                  e.printStackTrace();

            }

      }

 

      protected void processDownload(

            HttpServletRequest req,

            HttpServletResponse resp)

            throws Exception {

int docId = Integer.valueOf(req.getParameter(”doc_id”)).intValue();

String docName = req.getParameter(”manualName”);

String fileType =

      docName.substring(docName.indexOf(”.”) + 1, docName.length());

 

FileVO fileVO = null;

 

fileVO = UploadFileDAO.getDocDownload(docId);

 

if (fileType.trim().equalsIgnoreCase(”txt”)) {

      resp.setContentType(”text/plain”);

} else if (fileType.trim().equalsIgnoreCase(”doc”)) {

      resp.setContentType(”application/msword”);

} else if (fileType.trim().equalsIgnoreCase(”xls”)) {

      resp.setContentType(”application/vnd.ms-excel”);

} else if (fileType.trim().equalsIgnoreCase(”pdf”)) {

      resp.setContentType(”application/pdf”);

} else if (fileType.trim().equalsIgnoreCase(”ppt”)) {

      resp.setContentType(”application/ppt”);

} else {

      resp.setContentType(”application/octet-stream”);

}

 

resp.setHeader(”Content-Disposition”,”attachment; filename=\”" + docName + “\”");

resp.setHeader(”cache-control”, “no-cache”);

 

ServletOutputStream outs = resp.getOutputStream();

outs.write(fileVO.getDocfile());

outs.flush();

outs.close();

 }

 }

 

 

The code to retrieve the document file from database is-

      public static FileVO getDocDownload(int docid){            ArrayList docList = new ArrayList();

            Connection dbConnection = null;

            PreparedStatement pstmt = null;

            ResultSet rset = null;

            FileVO filevo = null;

            try {

                        dataSource = lookUp(JNDI_NAME);

                        dbConnection = dataSource.getConnection();

                        pstmt = dbConnection.prepareStatement(DOC_DNLD_QRY);

                        pstmt.setInt(1,docid);

                        rset = pstmt.executeQuery();

                        while(rset.next()){

                        filevo = new FileVO();

                        filevo.setDoc_id(rset.getInt(”DOC_ID”));

                        filevo.setDoc_name(rset.getString(”DOC_NME”));

                        Blob b = rset.getBlob(”DOC”);

                        byte[] ba = b.getBytes(1,(int)b.length());

                        filevo.setDocfile(ba);

 

            System.out.println(”Size of byte[]::”+ba.length);

 

                        }

            } catch (SQLException sqe) {

                        sqe.printStackTrace();

            } catch (Exception e) {

                        e.printStackTrace();

            } finally{

             try{

                        rset.close();

                        dbConnection.close();

             } catch (SQLException sqe) {

                        sqe.printStackTrace();

             }

            }

            return filevo;

      }

 

The sample code for the FileVO object is-

 

public class FileVO implements Serializable {      private int doc_id;

      private String doc_name;

      private byte[] docfile;

     

      public int getDoc_id() {

            return doc_id;

      }

 

      public void setDoc_id(int i) {

            doc_id = i;

      }

 

And so on…

Blog Widget by LinkWithin

Related Articles:

  1. Tutorial on how to store images in Mysql BLOB field [caption id="attachment_78" align="alignleft" width="300" caption="mysql"][/caption] Sometimes in our web...
  2. Creating a struts project using Eclipse Ganymede Here is a short article that may help you while...
  3. How to load a properties file in Java This tutorial will explain how to access properties file through Java...
  4. JfreeChart Series-2: How to create a dynamic Pie Chart using JFreeChart library in Java  In the earlier tutorial I showed you how to create...
  5. JfreeChart Series-1: How to create a dynamic Bar Chart using JFreeChart library in Java In Java creating any graph or chart like bar chart...

Tags: , , , , , ,

1 Response to " File upload to BLOB field and display attachment dialog box "

  1. Ruthresan says:

    Good… Ur above code is very much useful n simple.. Y can,t u add the syntax n statements for creating database table.. If possible add it soon.. Thank U….

Leave a Reply

Spam Protection by WP-SpamFree

Copyright © 2009 TechCuBeTalk free technology magazine. All rights reserved.
Designed by Theme Junkie. Powered by WordPress.