Meyyappan has posted 101 posts at DZone. View Full User Profile

Struts File Upload Tutorial

06.15.2012
| 33437 views |
  • submit to reddit
In this tutorial we will see how to allow the user to upload a file using Struts. In order to allow the user to upload a file, we need to set the encoding type of html:form tag to "multipart/form-data" and specify the HTTP method as "post". The html:file tag enables the user to browse and select a file.
<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
    File : <html:file property="file" /> <br/>
    <html:submit />
</html:form>

The property file in the FileUploadForm is of type FormFile (org.apache.struts.upload.FormFile). We will check whether the file uploaded by the user satisfies the following conditions in the FileUploadForm's validate() method.

  • Should be an Excel File.
  • File size should not exceed 20kb.

The validate() method of the FileUploadForm contains the following code.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
    if (file.getFileSize() == 0) {
    	errors.add("file", new ActionMessage("error.file.required"));
    } else if (!file.getContentType().equals("application/vnd.ms-excel")) {
    	errors.add("file", new ActionMessage("error.file.type"));
    }
    /**
    * If the file size is greater than 20kb.
    */
    else if (file.getFileSize() > 20480) {
    	errors.add("file", new ActionMessage("error.file.size"));
    }
    return errors;
}

The getFileSize() method returns the size of the file. The getContentType() method returns the content type of the file selected by the user.

We save the file uploaded by the user in the server. To do this we first get the file uploaded by the user using the getFile() method. The getFile() mehtod returns a FormFile object. Using the FormFile object we can get details regarding the file like file name and file data.

The FileUploadAction contains the following code.

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
  FileUploadForm uploadForm = (FileUploadForm) form;
  FileOutputStream outputStream = null;
  FormFile formFile = null;
  try {
      formFile = uploadForm.getFile();
      String path = getServlet().getServletContext().getRealPath("")+"/"+
      formFile.getFileName();
      outputStream = new FileOutputStream(new File(path));
      outputStream.write(formFile.getFileData());
  } 
  finally {
      if (outputStream != null) {
          outputStream.close();
      }
  }
uploadForm.setMessage("The file "+formFile.getFileName()+" is uploaded successfully.");
return mapping.findForward(SUCCESS);
}

The getFileData() method returns the entire file as a byte[]. This method should be used only when the file size is small, incase of large files its better to use getInputStream() method.

On executing the example the following page will be displayed to the user.

When the user submits the form without selecting any file the following message is dispalyed to the user.


When the user selects a file other than an Excel file then the following message is dispalyed to the user.


When the user selects a file that is greater than 20kb then the following message is dispalyed to the user.


When the user selects an excel file that is less than 20kb, then the user is forwarded to the success page.



  • Download the example and copy it inside the webapps directory of the Tomcat sever.
  • Run the example using the following url "http://localhost:8080/Example23/".
  • Select an excel file to upload.
  • The excel file will be saved inside the Example directory in the server.
  • For example, when I uploaded the temp.xls file the file got stored in the following location "C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\Example23\temp.xls".


You can download the source code of the File Upload example by clicking on the Download link below.

Source :Download
Source + Lib :Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Hemant Singh replied on Fri, 2012/09/07 - 8:19am

i am getting this EXCEPTION

java.lang.ClassCastException

: org.apache.struts.action.ActionMessage cannot be cast to org.apache.struts.action.ActionError

Hemant Singh replied on Fri, 2012/09/07 - 8:57am

SEVERE:

IOException while loading persisted sessions: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile

java.io.WriteAbortedException

: writing aborted; java.io.NotSerializableException: org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.defaultReadFields(Unknown Source)

at java.io.ObjectInputStream.readSerialData(Unknown Source)

at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at org.apache.catalina.session.StandardSession.readObject(

StandardSession.java:1611)

at org.apache.catalina.session.StandardSession.readObjectData(

StandardSession.java:1070)

at org.apache.catalina.session.StandardManager.doLoad(

StandardManager.java:284)

at org.apache.catalina.session.StandardManager.load(

StandardManager.java:204)

at org.apache.catalina.session.StandardManager.startInternal(

StandardManager.java:470)

at org.apache.catalina.util.LifecycleBase.start(

LifecycleBase.java:150)

at org.apache.catalina.core.StandardContext.startInternal(

StandardContext.java:5282)

at org.apache.catalina.util.LifecycleBase.start(

LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(

ContainerBase.java:1568)

at org.apache.catalina.core.ContainerBase$StartChild.call(

ContainerBase.java:1558)

at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)

at java.util.concurrent.FutureTask.run(Unknown Source)

at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

at java.lang.Thread.run(Unknown Source)

Caused by:

java.io.NotSerializableException: org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile

at java.io.ObjectOutputStream.writeObject0(Unknown Source)

at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)

at java.io.ObjectOutputStream.writeSerialData(Unknown Source)

at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)

at java.io.ObjectOutputStream.writeObject0(Unknown Source)

at java.io.ObjectOutputStream.writeObject(Unknown Source)

at org.apache.catalina.session.StandardSession.writeObject(

StandardSession.java:1687)

at org.apache.catalina.session.StandardSession.writeObjectData(

StandardSession.java:1087)

at org.apache.catalina.session.StandardManager.doUnload(

StandardManager.java:411)

at org.apache.catalina.session.StandardManager.unload(

StandardManager.java:353)

at org.apache.catalina.session.StandardManager.stopInternal(

StandardManager.java:497)

at org.apache.catalina.util.LifecycleBase.stop(

LifecycleBase.java:232)

at org.apache.catalina.core.StandardContext.stopInternal(

StandardContext.java:5462)

at org.apache.catalina.util.LifecycleBase.stop(

LifecycleBase.java:232)

at org.apache.catalina.core.ContainerBase$StopChild.call(

ContainerBase.java:1583)

at org.apache.catalina.core.ContainerBase$StopChild.call(

ContainerBase.java:1573)

... 5 more

Sep 07, 2012 6:25:20 PM org.apache.catalina.session.StandardManager startInternal

SEVERE: Exception loading sessions from persistent storage

java.io.WriteAbortedException

: writing aborted; java.io.NotSerializableException: org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.defaultReadFields(Unknown Source)

at java.io.ObjectInputStream.readSerialData(Unknown Source)

at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at org.apache.catalina.session.StandardSession.readObject(

StandardSession.java:1611)

at org.apache.catalina.session.StandardSession.readObjectData(

StandardSession.java:1070)

at org.apache.catalina.session.StandardManager.doLoad(

StandardManager.java:284)

at org.apache.catalina.session.StandardManager.load(

StandardManager.java:204)

at org.apache.catalina.session.StandardManager.startInternal(

StandardManager.java:470)

at org.apache.catalina.util.LifecycleBase.start(

LifecycleBase.java:150)

at org.apache.catalina.core.StandardContext.startInternal(

StandardContext.java:5282)

at org.apache.catalina.util.LifecycleBase.start(

LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(

ContainerBase.java:1568)

at org.apache.catalina.core.ContainerBase$StartChild.call(

ContainerBase.java:1558)

at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)

at java.util.concurrent.FutureTask.run(Unknown Source)

at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

at java.lang.Thread.run(Unknown Source)

Caused by:

java.io.NotSerializableException: org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile

at java.io.ObjectOutputStream.writeObject0(Unknown Source)

at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)

at java.io.ObjectOutputStream.writeSerialData(Unknown Source)

at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)

at java.io.ObjectOutputStream.writeObject0(Unknown Source)

at java.io.ObjectOutputStream.writeObject(Unknown Source)

at org.apache.catalina.session.StandardSession.writeObject(

StandardSession.java:1687)

at org.apache.catalina.session.StandardSession.writeObjectData(

StandardSession.java:1087)

at org.apache.catalina.session.StandardManager.doUnload(

StandardManager.java:411)

at org.apache.catalina.session.StandardManager.unload(

StandardManager.java:353)

at org.apache.catalina.session.StandardManager.stopInternal(

StandardManager.java:497)

at org.apache.catalina.util.LifecycleBase.stop(

LifecycleBase.java:232)

at org.apache.catalina.core.StandardContext.stopInternal(

StandardContext.java:5462)

at org.apache.catalina.util.LifecycleBase.stop(

LifecycleBase.java:232)

at org.apache.catalina.core.ContainerBase$StopChild.call(

ContainerBase.java:1583)

at org.apache.catalina.core.ContainerBase$StopChild.call(

ContainerBase.java:1573)

... 5 more

Sep 07, 2012 6:25:20 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.util.LocalStrings', returnNull=true

Sep 07, 2012 6:25:20 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.action.ActionResources', returnNull=true

Sep 07, 2012 6:25:21 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='/java.resources/application', returnNull=true

Sep 07, 2012 6:25:21 PM org.apache.struts.validator.ValidatorPlugIn initResources

INFO: Loading validation rules file from '/WEB-INF/validator-rules.xml'

Sep 07, 2012 6:25:21 PM org.apache.struts.validator.ValidatorPlugIn initResources

INFO: Loading validation rules file from '/WEB-INF/validation.xml'

Sep 07, 2012 6:25:21 PM org.apache.coyote.AbstractProtocol start

INFO: Starting ProtocolHandler ["http-bio-8080"]

Sep 07, 2012 6:25:21 PM org.apache.coyote.AbstractProtocol start

INFO: Starting ProtocolHandler ["ajp-bio-8009"]

Sep 07, 2012 6:25:21 PM org.apache.catalina.startup.Catalina start

INFO: Server startup in 7837 ms

Sep 07, 2012 6:25:25 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.taglib.html.LocalStrings', returnNull=true

Sep 07, 2012 6:25:25 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.taglib.html.LocalStrings', returnNull=true

Sep 07, 2012 6:25:25 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.util.LocalStrings', returnNull=true

Sep 07, 2012 6:25:25 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.taglib.html.LocalStrings', returnNull=true

Sep 07, 2012 6:25:25 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.taglib.html.LocalStrings', returnNull=true

Sep 07, 2012 6:25:25 PM org.apache.struts.util.PropertyMessageResources <init>

INFO: Initializing, config='org.apache.struts.taglib.html.LocalStrings', returnNull=true

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.