Posts Tagged ‘file upload’

Uploading a file with Flex 3 and Struts 2

Monday, August 31st, 2009

In my previous post I taught you how to upload a file using Struts 2. In the example I gave you, both the presentation layer and the code that received the file were done in Struts 2.
But what if you want to upload a file via Adobe Flex? How can you do it?

The FileReference flex class allows you to upload files from a client to a server. In our case a server running Struts 2. FileReference shows a dialog box that allows the user to select which file to upload.
Enough of theory. Below is an example of the code that you can use to upload a file to a server running struts 2:

Step 1

First you need to create the dialog box that will allow the user to select a file to upload by clicking the button “Browse”.

<mx:VBox width="100%" left="10" top="10" >
   <mx:HBox>
       <mx:Label text="Image to upload:"/> <mx:TextInput disabledColor="black" enabled="false" id="fileName" width="200"  />
              <mx:Button width="80" label="Browse" click="browseFiles()" />
   </mx:HBox>
          <mx:Button id="uploadButton" label="Upload" enabled="false" click="upload()"/>
          <mx:ProgressBar labelPlacement="center"  source="{fileRef}" label="%3%%" minimum="0" maximum="100" color="blue" height="13" width="100" id="progressBar" visible="false" includeInLayout="false" />

        </mx:VBox>

Step 2

Create an object of type FileReference and add event listeners to track progress of the upload:

 fileRef = new FileReference();
 fileRef.addEventListener(Event.COMPLETE, completeEvent);
 fileRef.addEventListener(Event.SELECT, selectEvent);
 fileRef.addEventListener(IOErrorEvent.IO_ERROR, showError);
 fileRef.addEventListener(ProgressEvent.PROGRESS, progressEvent);
 fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, showError);

Step 3

Write the actionscript code that opens a dialog that calls the native “Open File Dialog” in the user’s operating system.

private function browseFiles():void {
      var validFiles:Array= new Array(new FileFilter("Images (*.jpg,*.png,*.gif,*.jpeg)", "*.jpg;*.png;*.gif;*.jpeg"));
      this.fileRef.browse(validFiles);
   }

Step 4

Write the actionscript code that uploads the file to the server.
In our previous example the struts 2 action for the upload is “/fileUpload”.
Therefore we use the following url to upload the file: ${baseUrl}/fileUpload

/**
   * Uploads a file to the server
   *
   */
   private function upload():void {
     mx.controls.Alert.show("Starting upload.");
     var sendVars:URLVariables;
     var request:URLRequest;
     sendVars = new URLVariables();
     request = new URLRequest();
     request.data = sendVars;
     request.url =baseUrl + "/fileUpload";
     request.method = URLRequestMethod.POST;
     fileRef.upload(request,"file",false);
   }

You can find sample code to upload a file here. Note however that the example only works with a server to receive the file.

Uploading a file with Struts 2

Monday, August 31st, 2009

Uploading a file with Struts 2 is really simple with the help of the FileUploadInterceptor. The steps required to upload a file using Struts 2 are:

Step 1

Create the Struts 2 Action class. In our example we have called it FileUploadAction.java

An example of an action to upload a file:

package uk.co.spltech.web.actions;

import com.opensymphony.xwork2.Action;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Uploads a file using Struts 2
 *
 * @author Armindo Cachada
 */
public class FileUploadAction extends ActionSupport {
     private static final long serialVersionUID = 12323232L;
     private File file;
     private String fileFileName;
     private String fileContentType;

 public String execute() {

  return Action.SUCCESS;
 }

 public File getFile() {
        return this.file;
     }

  public void setFile(File file) {
         this.file = file;
      }

  public void setUpload(File file) {
      this.file = file;
   }
 /**
       * This method is called by the action.
       * Here you can do whatever you want with the uploaded file
       */
 public String upload() throws IOException  {
        File uploadedFile =this.getFile();
        // you can do whatever you want with the file
        return Action.SUCCESS;
 }

 public String getFileFileName() {
  return fileFileName;
 }

 public void setFileFileName(String fileFileName) {
  this.fileFileName = fileFileName;
 }

 public String getFileContentType() {
  return fileContentType;
 }

 public void setFileContentType(String fileContentType) {
  this.fileContentType = fileContentType;
 }

 public String getFileUrl() {
  return fileUrl;
 }

 public void setFileUrl(String fileUrl) {
  this.fileUrl = fileUrl;
 }
}

Step 2

Create the action in struts.xml

<action name="fileUpload" class="uk.co.spltech.web.actions.FileUploadAction" method="upload">
 <result>/success.jsp </result>
 <result type="error">/upload.jsp</result>
</action>

Step 3

Create the jsp. For example:

Please select the file you want to upload:

 <s:form action="fileUpload" method="post" enctype="multipart/form-data" theme="simple">
  <s:actionerror cssClass="errorMessage"/>
  <s:fielderror cssClass="error"/>
      <s:file name="upload" label="File"/>
     <s:submit/>
 </s:form>

Step 3

The default maximum file size that struts 2 allows you to upload is only 2 megabytes. You can increase this size by specifying in struts.properties the struts.multipart.maxSize. This value is in bytes.
For example:

struts.multipart.maxSize=20480

Finally you can download the code for this example here.

Note that I didn’t include the required struts2 library files with the example.
The files you need are:

commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging.jar
freemarker-2.3.13.jar
ognl-2.6.11.jar
struts2-core-2.1.6.jar
xwork-2.1.2.jar
struts2-convention-plugin-2.1.6.jar


Click here to learn how to upload a file with Adobe Flex