Uploading files in Flex using the FileReference class

by Peter deHaan on September 21, 2007

In an earlier example we looked at “Downloading files in Flex using the FileReference class“, but It looks like we haven’t ever looked at file uploads.
The following example shows how you can use the FileReference class’s browse() method to allow users to select and upload a single file to a Web server.

If you want to allow users to upload multiple files at once, you would use the FileReferenceList class instead of FileReference.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            private var fileRef:FileReference;

            private const FILE_UPLOAD_URL:String = "http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm";

            private function init():void {
                fileRef = new FileReference();
                fileRef.addEventListener(Event.SELECT, fileRef_select);
                fileRef.addEventListener(ProgressEvent.PROGRESS, fileRef_progress);
                fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
            }

            private function browseAndUpload():void {
                fileRef.browse();
                message.text = "";
            }

            private function fileRef_select(evt:Event):void {
                try {
                    message.text = "size (bytes): " + numberFormatter.format(fileRef.size);
                    fileRef.upload(new URLRequest(FILE_UPLOAD_URL));
                } catch (err:Error) {
                    message.text = "ERROR: zero-byte file";
                }
            }

            private function fileRef_progress(evt:ProgressEvent):void {
                progressBar.visible = true;
            }

            private function fileRef_complete(evt:Event):void {
                message.text += " (complete)";
                progressBar.visible = false;
            }
        ]]>
    </mx:Script>

    <mx:NumberFormatter id="numberFormatter" />

    <mx:Button label="Upload file"
            click="browseAndUpload();" />
    <mx:Label id="message" />
    <mx:ProgressBar id="progressBar"
            indeterminate="true"
            visible="false" />

</mx:Application>

View source

You’ll notice the previous example doesn’t have a SWF or file upload URL. That would be because I don’t want all of you uploading files to my server. :)

In the previous example, I wrapped the call to fileRef.size in a try..catch block. In ActionScript 3.0, Flash Player throws an error if you attempt to get the size of a zero-byte file.

{ 84 comments… read them below or add one }

John July 21, 2009 at 9:14 pm

I want create DirectoryDialog and I need get full path of directory, is any idea how is create ?
And it possible?

Reply

Naju July 31, 2009 at 3:27 am

Hi all ,

I am facing a problem while uploading file from windows systems , from Linux systems it is working fine

I used fileReference class to upload .

and also when running in the local network it works both in windows and Linux .

when deploying on a server only the problem arising

Please help ….

Reply

Rahil August 1, 2009 at 12:54 am

how to unload the temp.internet files

Reply

alchemist October 1, 2009 at 8:37 am

Here’s a another great example multiple file uploading which also uses the FileReference class

http://bytearray.brixtonjunkies.com/2009/10/01/flex-multiple-file-uploader/

Reply

Tim Wilson October 21, 2009 at 1:50 pm

I’m also new to flex, and need someone to give me a helping hand. I would like to upload an image to my server without browsing for it. I’m using snapshot to capture an component (works fine) but now I need to get the snapshot to the server.. any ideas?? Thank you

Reply

Peter deHaan October 21, 2009 at 2:08 pm

@Tim Wilson,

I’ve never tried that, but you may be able to take your snapshot and convert it to Base64 (see “Using the ImageSnapshot class to capture images as JPEGs or PNGs in Flex 3″) and then POST it to your server using HTTPService or something similar. Then have your server-side script write the bits to disk.

Peter

Reply

Tim Wilson October 21, 2009 at 3:00 pm

Thanks Peter! I haven’t quite reached my goal yet – but I have been able to display the base64 content as a image on the server and save it to a file – I just need to send the contents from flex to the server and I should be close to what I needed – Thank you very much!

Mohamed Allam October 21, 2009 at 5:41 pm

Hello All, i need your support please i’m trying to upload a file from a simple flex application i created as shown above.

but in the url i’ve it as follow
FILE_UPLOAD_URL:String=”http://localhost/cfma.cfm”;

i’m not sure about this cfm folder and i dont know what should be written inside this file and where it should be?

your help will be much appreciated.

Reply

Peter deHaan October 21, 2009 at 7:10 pm

@Mohamed Allam,

I posted the rough ColdFusion code I used in the comments (you may have to click the “Previous Comments” link above) at http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/comment-page-1/#comment-1253

There are also other examples in other (non-ColdFusion languages) in the comments.

Peter

Reply

Mohamed Allam October 22, 2009 at 5:39 am

Dear Peter deHaan,

Would like to thank you so much for your instant reply, i really appreciate it, well i try both the cf solution and the .Net one but i get the same issue which is
i/o error : [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2038: File I/O Error. URL: http://localhost/weborb30/FileUpload-debug/Uploaded/upload.cfm"]

and normal Error : [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=405]

i’ve also tried my destination=”http://localhost/Allam/ and once as follow destination=”C:/Allam” both got rights to access

Your help will be much appreciated.

Thanks in Advance.

Reply

Peter deHaan October 24, 2009 at 10:40 am

@Mohamed Allam,

I recommend taking Flex/Flash Player out of the equation and just testing your server side script first. I don’t know why you’re getting the 405 HTTP status code, but it will be a lot easier if you get you can debug your server scripts using HTML/ColdFusion/ASP/<whatever> before trying to figure out how to get FileReference to send data to the server.

Peter

Reply

Stephen P October 23, 2009 at 10:59 pm

Is it possible to send varibles along to the server at the same time as file upload? Let say I have a data model and want to use that information to create a directory on the server with PHP which is processing my image uploads. Needs to be done at the same time the file is being uploaded so PHP can MKDIR related to that user.

Any ideas?

Reply

Peter deHaan October 24, 2009 at 10:41 am

@Stephen P,

I haven’t played with FileReference+URLVariables in a while, but you can try checking this out and see if it works for you; “Using the URLVariables and FileReference classes to pass data from Flex to a server-side script”.

Peter

Reply

jp December 7, 2009 at 7:08 am

Hi,
Has anyone here used filereference to upload files to ftp server.
I used the code from following url – http://ntt.cc/2009/08/23/how-to-upload-files-in-flex-ftp.html
works for everyone there in forums but not for me. If it you succeeded can you post your code please.

I’d appreciate suggestions!
Thanks.

Reply

sabeerdeen January 12, 2010 at 1:17 am

hi..
i didnt find the uploaded file saved in web server!
can any one help?

Reply

Nicolas January 24, 2010 at 3:28 pm

I have acheived success with a php script as the target file in stead of uploader.cfm file

At first it didn’t work as I was running the MXML script from within Flex which was then accessing my server –
When I ran it from my local server it worked.

http://www.zambala.net/public/phpUploaderScript.txt

Reply

Robert Morse February 19, 2010 at 5:30 am

Under Flash Builder 4 (Beta 2) and Flash Player 10, there is a security exception during the fileRef_select:

SecurityError: Error #2000: No active security context.

I believe this is Flash Player related, but I’m not clear on what the fix is. Any suggestions?

Reply

Sandy April 1, 2010 at 10:35 am

Hi,

If I run this example from Flex or from the bin-debug folder, it works fine. But, if I copy the content to another folder, when I click the upload button, it doesn’t start to upload the file. Do you know why I can’t to run the application in another folder?

Thanks

Reply

Peter deHaan April 1, 2010 at 5:17 pm

@Sandy,

Are you trying it in some other folder on your hard drive? Or some other folder on your web site?

Peter

Reply

Sandy April 2, 2010 at 12:44 am

Hi,

Thanks for your quick answer. If I try in another folder in the harddisk, When I click the upload button, show the file size, but don’t start to upload the file an don’t show the progress bar . It only works in the bin-debug folder.

Thanks

Reply

Peter deHaan April 2, 2010 at 8:11 am

@Sandy,

Almost all my experience is with running SWF files from the Internet and not directly from my hard drive somewhere, but I believe you need to look into your FlashPlayerTrust settings. I’m using Win7 and my FlashPlayerTrust folder is at: E:\Users\peter\AppData\Roaming\Macromedia\Flash Player\#Security\FlashPlayerTrust

In that folder there seems to be a “flashbuilder.cfg” file (I’m using Flash Builder 4), and the file has the following contents:

E:\Program Files\Adobe\Adobe Flash Builder 4\plugins\com.adobe.flexbuilder.ui_4.0.0.272416\welcome
E:\Users\peter\Adobe Flash Builder 4
E:\Users\peter\Documents\..\Adobe Flash Builder 4

I believe you can just add other folders in there as well (for example, add “C:\” to trust everything on your C:\ drive). Also, you can go to the Flash Player Global Security Settings panel on adobe.com and try adding the location of your SWF folder on your harddisk and see if that helps.

Peter

Reply

Sandy April 5, 2010 at 4:59 am

Hi,

Changing the FlashPlayerTrust settings it works. I have added permisions to the folder that contains the project. Tomorrow I will try from a web because I think that I have the same problem.

Thank You for your help that was very succesfully for me

Reply

Sandy April 6, 2010 at 2:37 am

Hi,

Im running the application in the server. If I run the application with doble click in the ´.html it works fine, but if I start the application from explorer with http://localhost then it doesn’t work. Do you know what happnes.

Thank You

Reply

Sandy April 7, 2010 at 3:57 am

Hi,

I have solved the problem. The problem was that I have the web site in one server and it upload the files to another server. If I upload the files to the same server it works fine. Now I’m going to make tests with the crossdomain because I think the problem is with permissions.

Thanks again for your help

Reply

Yao April 14, 2010 at 11:46 am

Flex applicaton crashes on larg file (>200MB) by using load() method of FileReference load. Does anyone know the solution? Thanks!

Reply

ivan April 29, 2010 at 4:47 pm

Hi anyone know how to do this with amfphp 1.9 or it’s imposible, im working on air fles sdk 3.5

Thanks

Reply

redseven3 May 25, 2010 at 1:08 pm

is there a way to populate the fileRef information without calling the browse method? I know where the file is located to upload and I want it to auto-upload in the background without any user intervention

Reply

Peter deHaan May 25, 2010 at 10:09 pm

@redseven3,

As far as I know, FileReference actions must be user initiated and cannot be done without any user intervention. Otherwise you would potentially be allowed to write Flex applications that would upload user’s system files without their permission.

Peter

Reply

Murali June 2, 2010 at 4:24 am

For all the guys using servlets, there is an issue in maintaining sessions with FileReference in Flash. Append ‘;jsessionid=’ + sessionId to get it working.

Reply

Ruben June 7, 2010 at 3:34 pm

Murali,

I just ran into the problem where FileReference dosen’t maintain the sessionId. So how do I get the sessionId from within Flex/Flash? Is this a call to FlexGlobals or something else? For all my other requests that I make the sessionId is maintained transparently. I’m using java servlets in the backend.

Thanks

Reply

Peter deHaan June 7, 2010 at 5:17 pm
vijay June 16, 2010 at 4:09 am

Nice Example

Hi,
I m facing a problem when i used a combo box as a item editor in AdvanceDatagrid in flex.
When i click on particular cell then combobox will be visible it is ok but background text mins(advancedatagrid cell text) also visible. which is not looking good.

Please give me a solution if all of u have.
Thank you in advance

Reply

santi July 27, 2010 at 7:48 am

Hi,

I have a question about the flex upload. After select multiple file to upload, is posible to remove a file from the list upload before upload?

Thank you in advance for the help

Reply

Brun0o August 20, 2009 at 6:32 am

Sclark,

Sorry my english is bad.
You is solved ?
I have a exactly problem…

Tks
Bruno
Brazil

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: