Uploading files in Flex using the FileReference class

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.

145 thoughts on “Uploading files in Flex using the FileReference class

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

  2. 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!=)

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

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

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

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

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

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

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

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

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

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

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

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

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

  16. 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……

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

  18. i’m using backend ASPX (C#) , but it doesn’t work in visual 2005 ! Who can give me full demo upload ! Thank !

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

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

  21. Hi, great post, but I have a little problem in my method for browsing files:

    fr = new FileReference();
    fr.addEventListener(Event.SELECT, onSelectFile);
    fr.browse();
    

    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")]);
    
  22. 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

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

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

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

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

  27. hi ,

    no one can gave reply , what peter just give me idea about the cache by deleting the temp..internet files

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

  29. 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 ….

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

      1. 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!

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

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

    1. @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

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

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

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

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

    1. @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 FilesAdobeAdobe Flash Builder 4pluginscom.adobe.flexbuilder.ui_4.0.0.272416welcome
      E:UserspeterAdobe Flash Builder 4
      E:UserspeterDocuments..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

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

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

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

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

Comments are closed.