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.
<?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>
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.

{ 100 comments… read them below or add one }
← Previous Comments
Hi, i’ve got another problem. I need to create a real-time graph application, does anyone have an example? The graph should increase on the x axis each tick. Anyone has any idea?
Hello everybody!
I’v learn about Flex and server-side techologies less then month ago. I’ll be very glad, if somebody, step by step, describes me how can I force my Flex application to upload generated-in-time file to TomCat server using some Java technologies…
Thank you!=)
Hi all!
I have a problem with Upload file with FileReference.
I want to get path of file which i browse from client.
But i can’t get it!
Everyone can help me in this case, please!
Thanks for reading my problem.
Mai Ta,
I don’t believe that Flash Player returns that information (possibly for security reasons).
You could try searching for a bug/enhancement in the public Flash Player bug base at http://bugs.adobe.com/flashplayer/. Feel free to file a bug/enhancement if one doesn’t already exist. If you post the bug number here a few of us can vote and/or subscribe.
Thanks,
Peter
Hi Peterd!
Thanks for your reply!
So do you have any resolve for my problem?
I really need to get this path file for my project.
I don’t see any examples for this problem.
Sorry because of my problem!
Thanks,
Mai
Mai Ta,
I am not aware of any solutions or workarounds for this problem.
You could try asking on FlexCoders or some other list with lots of traffic and see if anybody has any ideas, but as far as I know, it is not possible to get the full path of a file when doing a file upload with the FileReference class and Flash Player.
Sorry,
Peter
Hi Peterd!
Thanks for your help very much!
Maybe i will change the way to upload file in Flex or only get file name in my project.
Thank you so much!
Nice day to u!
Thanks,
Mai
hi! petered!!
I can’t get xml string encoded by euc-kr when UPLOAD_COMPLETE_DATA event is occured.
I checked correct xml string on html, tomcat logs.
But only in Flex, xml string was bloken.
Plz help me ~~~ lol.
ps. There is no problem with HTTPService request/response.
public function fileRequest(url:String):void
{
var urlRequest:URLRequest = new URLRequest(url);
urlRequest.method = "POST";
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, fileResultHandler);
file.upload(urlRequest,"FileData",false);
}
--------------------------------------------------------
HTML, Tomcat Log
--------------------------------------------------------
테스트1
01000000001
abc1
--------------------------------------------------------
FLEX
--------------------------------------------------------
źƮ1
01000000001
abc1
euni,
Sorry, I don’t know why that would happen with euc-kr. Can you file a bug at http://bugs.adobe.com/flashplayer/ and attach any source code or files you think are relevant and somebody on the Player team may be able to have a look.
Peter
Hi
I’ve been trying to make this work using java spring as backend. But I can’t make it work. Spring has an implementation for file upload and Im using that as my backend.
Anyone out there got any idea how to do this?
Thanks :D
Hi Peter, how can i prevent the SecurityError: Error #2148: when i’m uploading files from my local desktop to an outside-the-sandbox-server. I tried a lot of hacks (crossdomain.xml, Security.allowDomain, eg) but this error, everytime appears. But the funny thing is, that the upload is complete, but i didn’t get any data from the server, that gives succes. Locally with localhost everything works finest.
Sorry Peter, just ignore my last comment – it was not the fault of the filereference, but i did something wrong with the data that was sent from the server
I am working on an AIR app. that records videos, using RED5. Once the user is happy with a video the app uploads the flv to a Windows server.
It works fine for short videos (small files), but when the file size is larger (I don’t know the threshold) it does not work anymore.
Do you know how to allow the app. or the asp.net script to work with large files?
Thanks.
I try to to upload a image to a server, but often the images are huge and I need to resize them before I upload them. Is there a way for flex to do this on the client side so I don’t have to uploade 20mb and then resize it.
Help or an example is preciated.
Regards
Ronny
Ronny,
I’ve never tried resizing images/BitmapData before uploading it to a server-side script.
You may want to try asking on the FlexCoders mailing list and see if anybody there has any suggestions.
Sorry,
Peter
greets,
nice blog ;)
I have a question about that fu… ahm nice ;) file upload feature after messing around with it a few ours long. So, here my prob: I’m using the aspx and I’ll say it’s working. I set all the events I need but in that special case the httpStatusEvent says nothing, only the openEvent stucks on [Event type="open" bubbles=false cancelable=false eventPhase=2] progress bar says it’s ready but there is no file in the directory (and yeah I set allready all the rights to that spec. dir.)
Somebody an idea?
thanks a lot.
jimmi
I’m trying to upload files and it works great in Windows, but on OS X it doesn’t ever hit my URLRequest page. Is there any insight on what is different between the two, or something I need to do in for OS X?
Hi Everyone,
Can any one help me to convert any type of Video files into .flv format (i.e) flash video format.
I mean, if we browse and select any type of video, it (Flex Program) should convert it to .flv format.
Thanks in Advance……
Hey there,
I have been trying to get a demo working of our fileuploadservlet. The servlet doesn’t do much at this point, and it’s running with standalone oc4j locally on my windows xp system.
I’m using the flex code as documented. I use a filefilter to get only csv files and I have a small test file.
The problem is the second I hit upload, I get the io error: Error #2044: Unhandled uploadIoError:. text=Error #2038: File I/O
I put some alert messages in and it appears this is happening before the upload has a chance to start. I event tried a different unix test server with an upload.php file (which I’ve pinged via browser and it responds) and still the same error.
My company uses a proxy so I’ve removed that (working from home, no firewall). No change. I have strong listeners (not weak).
I’ve added some variables to the URLVariables, but that’s it. It’s pretty plain vanilla, but it’s not playing nice.
This is on Windows XP. So the first scenario was all local – localhost, etc. The second scenrio was on another server I pay for…on unix that supports php and still the same immediate io error.
Any assistance would be greatly appreciated!
Spencer
Sclark,
Sorry my english is bad.
You is solved ?
I have a exactly problem…
Tks
Bruno
Brazil
I want to pass some custom paramters also with the file upload. How can i do that?
i’m using backend ASPX (C#) , but it doesn’t work in visual 2005 ! Who can give me full demo upload ! Thank !
I need to implement this with asp.net.I need to know that how I can add that in my html?
I am building a project wherein I have a browse button to allow to load an image from his local disk. The problem is that the user is being able to select the image but for uploading it to the server I need to write the code in JSP. Can someone please help me with this? I have searched the net and found many examples in PHP but not JSP. I am not much fluent with JSP and have absolutely no idea about PHP, so please help me with the JSP code.
Is there any way in Flex to re-order the POST parameters? I am trying to upload a file to a web service that expects the parameters in a certain order, and because it appears that this order is hard-coded.
Hi, great post, but I have a little problem in my method for browsing files:
Problem is when I do like this I can’t see all file types, only txt, jpg etc. I want to be able to upload pdf files, I try with filters but no :(
fr.browse([new FileFilter("PPack", "*.jpg;*.jpeg;*.gif;*.png;*.tiff;*.tif;*.pdf")]);Vlada,
This seems to work for me:
<?xml version="1.0" encoding="utf-8"?> <mx:Application name="FileReference_FileFilter_test" xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white"> <mx:Script> <![CDATA[ private var fileRef:FileReference; private function btn_clickHandler(evt:MouseEvent):void { var filters:Array = []; filters.push(new FileFilter("PPack", "*.jpg;*.jpeg;*.gif;*.png;*.tiff;*.tif;*.pdf")); fileRef = new FileReference(); fileRef.addEventListener(Event.SELECT, fileRef_select); fileRef.browse(filters); } private function fileRef_select(evt:Event):void { trace("You selected some files or something:", evt.currentTarget.name); } ]]> </mx:Script> <mx:Button id="btn" label="Click to select a file" click="btn_clickHandler(event);" /> </mx:Application>(Well, the code doesn’t really *do* anything, but at least I could browse my hard drive and select a file with a *.pdf extension.)
Peter
I’m new to Flex. I’m trying to find the simplest way to select a file from the local file system, load it into Flex (not Air) application, process it on the client side (without sending it to server), and display the results. I cannot use FileReference for that. Any alternatives/workarounds ?
Thanks
Evgeni,
I am not 100% certain, but I don’t think that is possible. Flash Player shouldn’t be able to access the user’s file system without using FileReference/AIR as it would be a security risk.
Peter
hi ,
how to delete files in flex ,
rahil,
How would a Flex app delete files on a client’s computer? It can’t.
How would a Flex app delete files on the server? You’d need to use a server side script (using ColdFusion, Java, PHP, Perl, .NET, etc).
Peter
hi peter,
What my question is , how to use the cache in flex and how to delete the files in local/server temparery folder ..
My requiment is ..
4
If page 1 loaded then pages 2,3,4,5 are loaded.
When reader opens page 4 (and 5) then application understands that it needs to load more pages next 4 pages are loaded – pages 6,7,8,9. Pages 1,2,3 unloaded
Reader turns to page 6,7 – no actions
Reader turns to page 8, 9 – 10,11,12,13 are loaded – pages 4,5,6,7 unloaded
If reader goes to page 22/23 pages 22,23,24,25 loaded – all other pages unloaded
If reader then turns to previous pages 20/21 then 20,21 loaded
If reader turns to 18/19 then 18/19 loaded
So Peter u understood my prb… I need code for this ASAP …
Than x peter
hi ,
no one can gave reply , what peter just give me idea about the cache by deleting the temp..internet files
any plain java example here which i can call via amf as remoteobject?
I want create DirectoryDialog and I need get full path of directory, is any idea how is create ?
And it possible?
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 ….
how to unload the temp.internet files
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/
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
@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
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!
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.
@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
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.
@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
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?
@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
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.
hi..
i didnt find the uploaded file saved in web server!
can any one help?
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
← Previous Comments