Wednesday, July 1, 2009

Uploading a file with Flex 3 and Struts 2

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:Label text="Image to upload:"/> <mx:TextInput disabledColor="black" enabled="false" id="fileName" width="200" />
<mx:Button width="80" label="Browse" click="browseFiles()" />
<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" />


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"));

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 {"Starting upload.");
var sendVars:URLVariables;
var request:URLRequest;
sendVars = new URLVariables();
request = new URLRequest(); = sendVars;
request.url =baseUrl + "/fileUpload";
request.method = URLRequestMethod.POST;

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

1 comment:

Sabeerdeen said...

if full source code for uploading a file is given, then it will be more useful for beginners like me.. ie.,struts (action form , action class, struts-config.xml)