Downloading files in Flex using the FileReference class

OK, enough embedding examples, lets take a look at downloading files using Flash Player’s FileReference class (flash.net.FileReference). This example demonstrates a basic usage of the FileReference class within Flex, allowing users to download a file from the server. This example also shows how you can use data tips in the DataGrid control by setting the data grid column’s showDataTips property to true and specifying a value for the dataTipField column.

Full code after the jump.

The following example downloads a ZIP file when the user presses the Button control. You can mouse over the items in the DataGrid control’s “Type” column to see additional event information.

Download source (ZIP, 3K) | View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/07/28/downloading-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[
            import mx.controls.Alert;
            import mx.collections.ArrayCollection;
            import flash.net.FileReference;
 
            [Bindable]
            [Embed('assets/disk.png')]
            private var diskIcon:Class;
 
            [Bindable]
            private var arrColl:ArrayCollection;
 
            /* URL of the file to download. */
            private const FILE_URL:String = "http://blog.flexexamples.com/wp-content/uploads/FileReference_download_test/bin/srcview/FileReference_download_test.zip";
 
            private var fileRef:FileReference;
            private var urlReq:URLRequest;
 
            private function init():void {
                /* Initialize the array collection to an empty collection. */
                arrColl = new ArrayCollection();
 
                /* Set up the URL request to download the file specified by the FILE_URL variable. */
                urlReq = new URLRequest(FILE_URL);
 
                /* Define file reference object and add a bunch of event listeners. */
                fileRef = new FileReference();
                fileRef.addEventListener(Event.CANCEL, doEvent);
                fileRef.addEventListener(Event.COMPLETE, doEvent);
                fileRef.addEventListener(Event.OPEN, doEvent);
                fileRef.addEventListener(Event.SELECT, doEvent);
                fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
                fileRef.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
                fileRef.addEventListener(ProgressEvent.PROGRESS, doEvent);
                fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
            }
 
            private function doEvent(evt:Event):void {
                /* Create shortcut to the FileReference object. */
                var fr:FileReference = evt.currentTarget as FileReference;
 
                /* Add event order and type to the DataGrid control. */
                arrColl.addItem({data:arrColl.length+1, type:evt.type, eventString:evt.toString()});
 
                try {
                    /* Update the Model. */
                    fileRefModel.creationDate = fr.creationDate;
                    fileRefModel.creator = fr.creator;
                    fileRefModel.modificationDate = fr.modificationDate;
                    fileRefModel.name = fr.name;
                    fileRefModel.size = fr.size;
                    fileRefModel.type = fr.type;
                    /* Display the Text control. */
                    txt.visible = true;
                } catch (err:*) {
                    /* uh oh, an error of sorts. */
                }
            }
 
            private function downloadSourceCodeZip():void {
                /* Clear existing array collection. */
                arrColl = new ArrayCollection();
                /* Hide the Text control. */
                txt.visible = false;
                /* Begin download. */
                fileRef.download(urlReq);
            }
 
            private function showAlert(item:Object):void {
                Alert.show(item.eventString, item.type);
            }
        ]]>
    </mx:Script>
 
    <mx:Model id="fileRefModel">
        <file>
            <creationDate>{""}</creationDate>
            <creator>{""}</creator>
            <modificationDate>{""}</modificationDate>
            <name>{""}</name>
            <size>{""}</size>
            <type>{""}</type>
        </file>
    </mx:Model>
 
    <mx:Button id="downloadBtn"
            label="Download example source code"
            icon="{diskIcon}"
            click="downloadSourceCodeZip();"
            toolTip="{FILE_URL}"
            height="40" />
 
    <mx:DataGrid id="debug"
            dataProvider="{arrColl}"
            width="{downloadBtn.width}"
            rowCount="5"
            rowHeight="22"
            itemClick="showAlert(event.currentTarget.selectedItem)">
        <mx:columns>
            <mx:DataGridColumn dataField="data"
                    headerText="#"
                    width="20" />
            <mx:DataGridColumn dataField="type"
                    headerText="Type"
                    showDataTips="true"
                    dataTipField="eventString" />
        </mx:columns>
    </mx:DataGrid>
 
    <mx:Text id="txt" condenseWhite="true" visible="false">
        <mx:text>
            creationDate: {fileRefModel.creationDate}
            creator: {fileRefModel.creator}
            modificationDate: {fileRefModel.modificationDate}
            name: {fileRefModel.name}
            size: {fileRefModel.size}
            type: {fileRefModel.type}
        </mx:text>
    </mx:Text>
 
</mx:Application>

View source enabled in the following example.

57 thoughts on “Downloading files in Flex using the FileReference class

  1. Good example working fine with your file…
    I modified the code to access one of my file from my HHTP server. It doesn’t work.
    I guess I should resolve the cross-domain issue.
    I placed a crossdomain.xml file into my server with the following content:

    Does not work!
    Do you have any idea?
    Thanks in advance!

  2. peterd,

    I hope you read comments to the older articles. I have noticed in the Flex help (both locally and on-line) that FileReference.download(…) does not use the HTTPStatusEvent. I have some code I have written and this seems to the be the case. However, you have set an event handler for it in this example and I want to know who’s right – you or the Flex help?

    Thanks.

  3. It´s possible update name of file to download

    For example i set in my var to

    private const FILE_URL:String = "http://127.0.0.1/FileDownload/service/file.cfm?ano=2008";
    

    is set to default file name to download file.cfm

    It´s possible Auto-update name to teste.txt ??

  4. hello. i copied and pasted this code and then ran it but got a “security error” when i tried to download file. can anyone help me out?

  5. private var fileRef:FileReference;
    private var urlReq:URLRequest;
    
    private function init():void {
        /* Initialize the array collection to an empty collection. */
        arrColl = new ArrayCollection();
    
        /* Set up the URL request to download the file specified by the FILE_URL variable. */
        urlReq = new URLRequest(FILE_URL);
    
        /* Define file reference object and add a bunch of event listeners. */
        fileRef = new FileReference();
        fileRef.addEventListener(Event.CANCEL, doEvent);
        fileRef.addEventListener(Event.COMPLETE, doEvent);
        fileRef.addEventListener(Event.OPEN, doEvent);
        fileRef.addEventListener(Event.SELECT, doEvent);
        fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, doEvent);
        fileRef.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
        fileRef.addEventListener(ProgressEvent.PROGRESS, doEvent);
        fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
    }
    

    :-)

  6. some way to change this code
    private const FILE_URL:String = “http://blog.flexexamples.com/wp-content/uploads/FileReference_download_test/bin/srcview/FileReference_download_test.zip”;

    to this way
    private const FILE_URL:String = textInput.text;
    or
    private var FILE_URL:String = textInput.text;
    some help please!

  7. Hi Peterd,
    good and useful script!
    but I have a question (and a problem) about file extension or file filter in dialog on windows.

    if the extension is known and hidden by folder option parameters than it doesn’t appear in the filename field:
    for example using filereference.download(urltosomefile,”dummy.doc”) i see in the filename field just “dummy” and in the type filter field “all file”.
    NOW TE PROBLEM:
    - if you don’t change the filename the extension is kipped
    - if you change the name you lost the extension

    Have you any idea to solve or work around this problem?

    thanks in advance,
    sandrokan

  8. Hi!
    Excuse my stypidness, but how can I download file generated just at time?
    In my case – I have some chart, and I want to download it’s screenshot. I have already read your article about “Taking screenshots in Flex 3 using the ImageSnapshot.captureBitmapData() method” (http://blog.flexexamples.com/2007/11/17/taking-screenshots-in-flex-3-using-the-imagesnapshotcapturebitmapdata-method/), so I have no problems about generating bitmap, byte array or just png/jpg file. But I don’t want to store it on my server – I just wish to download it to my local machine. Is it possible?

  9. Oh, sorry… I’v just read you article about uploading files, so now I have no questions… But, on the other hand – can you confirm my thoughts?
    If I want to download screenshot of some flex-displayed object I need:
    1) Write server-side script for getting file from running Flex Application
    2) Write flex application for uploading file using script from previous point
    3) Add to previous application methods for dowloading my file from server(At this point I should have it’s URL)

    Is it O.K.?

  10. Hoi,

    Verry nice exp:

    I have found a problem with the save dialog in IE7/Win Vista.

    I already tested in IE7/Win XP, and Firefox in Win and Mac and it works ok..

    I’m wondering if I’m the only one with this problem!

    Regards,
    Adil

  11. Thanks for this example. One note – fileRef needs to be defined globaly for file downloading to work. That’s how you have it in the example but I spent some time scratching my head when I did it differently and it broke. Thanks again

    -josh

  12. bhargavi,

    I’m not 100% certain, but I don’t think it is possible to automatically open a file on a user’s computer after the user has downloaded it.

    Peter

  13. Hi there!

    I was playing with this and PHP and found that if you try to download a file with zero-bytes length you will get an IOError… like the upload example [http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/]

    DSXP

  14. Hello and many thank for this grewat example!!

    i have just one problem, the same of sandrokan

    the file extension is Lost if you change the name :(

    any way to solve this problem?

    any help is very welcome :)
    thank you very much!

  15. Hello i am working on adding a Flex frontend to some of my existing stuff. I have a CSV export that is generated at runtime by

    http://domain.com/csv_export.php?mode=all

    It uses php header() to export a file in a browser. In IE my Flex says downloading but nothing happens. If I try in Firefox I get

    Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error.

    Has anyone seen this??

    Thx,
    Eric

  16. @Eric
    i ran into the same problem, the download dialog window lets me choose a file but then i get an IOError. Actually, the problem is that i defined my FileReference Object in the same function that i call the download() method. A quick workaround is to declare a dummy function or define your FileReference object outside the function.

    For more information:
    (in French)
    http://www.flex-tutorial.fr/2008/11/16/flex-filereference-ioerror-lors-de-lappel-a-download-resolu/
    (in English)
    http://blog.computerelibol.com/?p=17

    Fabien

  17. Hi Thanks for this great example. I used it in one of my applications for creating a flex downloader. This downloader fetches a list of files to be downloaded from the server. Once the list is retrived, on clicking the file names in the list it will open a save dialog box and start downloading the file.
    My concern is that, I need to create a downloader where in the destination folder is selected by the user for saving the files and then one by one the files are to be downloaded to that folder. Can any one show me some way to do it in Flex?

    Thanks for any help
    saji

  18. Hello,
    Thanks for ur greate example, i m facing a problem while downloading, once i downloaded the file and after it when i changes the content of file .. it is not reflected in new downloaded file,
    i need to restart the server ,
    please help.

    1. Hi,
      Did you find a solution/workaround for this problem? I am also facing the same problem. If I download a file and then update it and re-download it, I am not getting the updated contents. Interestingly, this is happening in IE only. It works fine in Firefox.

      Thanks.

  19. Hi! i’m beginning to move first step to Flex 3.0
    I need to find a sample to teach me how can i use FileReference Class for understand how i can do this:
    I need to open, with a button, a O.S. browse folder windowa to choose a xml file to show him into a datagrid… i have write the code for datagrid, controls and so onbut, but i don’t know how pass the file name selected to datagrid to show the nodes…
    can you help me please?
    Thanks a lot
    PS i read many of your sample very usefully and well explaned
    Bye
    Dave Zegna

  20. Dave,

    Welcome to Flex!
    First, I’d make sure you update your Flex Builder to the latest version (Flex Builder 3.0.2 with Flex SDK 3.2). For instructions, check out “Upgrading to Flex Builder 3.0.2″. This ensures you’re using the latest version of Flex Builder and the latest stable version of the Flex SDK (although you are able to download nightly builds of the Flex SDK which may include additional bug fixes). For more information, see “Downloading and installing Flex SDK builds from opensource.adobe.com” and “Using the beta Gumbo SDK in Flex Builder 3″.

    But, back to your question. Check out the FileReference archive on this site at: http://blog.flexexamples.com/tag/filereference/. Or more specifically, check out the following article: “Previewing an image before uploading it using the FileReference class in Flash Player 10″. I’m not sure if the latest version of Flash Player 9 has similar capabilities, but the previous solution was that after the user selected a file from their OS, you would need to upload the file to a server-side script and then download the file back to the client using FileReference again, and then you could parse the XML document and display it in a DataGrid or whatever. Personally, I think the easiest solution would be to use Flash Player 10 and following the “Previewing an image before uploading it using the FileReference class in Flash Player 10″ entry. Next, in the fileReference_complete() method I’d convert the fileReference.data property to an XML object and then set the DataGrid control’s data provider to an XMLList or XMLListCollection object. You may need to use some label functions to display the XML data correctly, but it should be fairly easy. The trickier part is that the user could select any file or the wrong type of XML document structure, so you may need to add some clever validation to ensure the XML data is what you expect.

    Happy Flexing!
    Peter

  21. Hi,

    I want to capture the request, read a file in the backend (java) and send it to the flex. Is it possible to do this way ?? Can u please suggest me with some idea if you come up with any ??

    Thanks,
    Madhav.

  22. First off, thanks for this and all your other tutorials/examples…excellent stuff!

    For security purposes, what if you wanted to access files that are below the web root (public_html) folder so that it is not directly accessible via a browser, but the script can access it?

    How would you do this for allowing users to download files that are secured in a folder below root?

    Thanks!
    Dan

  23. So like many others have recreated the example and it works when when I download the example file but not when I change it to my web site and referene a file there. It gets the 2038 i/o error. Thought it was a cross domain issue so I put in a crossdomain.xml file to let everything in but that didn’t eliminate the error.

    Any ideas or suggestions

  24. Hi,

    Thanks for nice example, One thing I notice that on file save dialog box a warning message appears (“Warning: This file may be an executable program or certain malicious content, use caution before saving or opening”). Is this possible to remove that message..?

    Thanks,
    Swapnil.

  25. Hi,

    just a update on above my comments, This warning is appears on flash player 10 onlu.

    Thanks,
    Swapnil.

  26. From what I’ve read about the FileReference class, it should be able to handle any file type. I haven’t had any problems downloading .doc, .xls, and .pdf files, but I do get errors when trying to download .xml and .txt and .log. Here’s an example of an xml file that won’t download:

    <?xml version=1.0 encoding=”UTF-8″?>
    <books>
        <book>
            <title>A Tale of Two Cities</title>
            <author>Charles Dickens</author>
        </book>
        <book>
            <title>Emma</title>
            <author>Jane Austen</author>
        </book>
        <book>
            <title>The Count of Monte Cristo</title>
            <author>Alexandre Dumas</author>
        </book>
    </books>

    The error I get upon trying to download this file is “Error #2038: File I/O Error”

    Does anyone else have problems downloading with .xml and .txt files?

    1. I have the same issue when downloading kml files and the user is using IE7 (using IE6 is working ok). Please let me know if you found a solution.
      thanks

  27. anyone having a problem on https? i have a code that works on http but for some reason i am getting an i/o error in https. can you help me out? tnx

  28. This is a nice example but one thing is missing the dowload progress bar if add to this solution that is a nice.

  29. I tried using the program on a very large file (about 20 meg). The file was downloaded, but was truncated. Any ideas of how to fix this … and what the problem might be?
    Thanks!
    John

  30. Hi,
    I have look your code of downloading files using flex, nice stuff. But I just want to download multiple files without convert them into zip or rar.
    Please help on this or let me know how can I do this.

    Thanks

    1. @mimoy,

      I don’t believe there is. It may be possible in Adobe AIR, but I’m somewhat certain that you cannot access the full path of the downloaded file using Flash Player (only the file name).

      Peter

    1. @bisteck,

      No, the save as dialog box is not optional. Flash Player does not allow you to automatically and non-interactively save file to the user’s file system.

      Peter

  31. Hey Peter

    Thank you for your sample code . It did help me. Your sample is simple and easy. Thanks once again.

    Now, i have a problem i want to download multiple files just as HIT has mentioned in his post. I managed to do that
    by looping over the fileRef. download() method . The problem is for each file i have to encounter the saveAs dialog box.
    This is a real pain . As in my application a user may choose to select 100 s of files together for download. Asking the user to
    enter 100 saveAs dialogs is not practical . Is there an alternative to this . I saw your response to mimoy , but i just needed to make sure

    The fileReference.download method does take in as input a file name. Couldnt that be used without having the file save as dialog ?

    1. @martin joseph,

      As far as I know, the Save As… dialog is required. A Flash/Flex application cannot just download files and automatically save them to a user’s machine. If you control the server, it may just be easier to pass a list of files to the server and have the server try and ZIP them up and send one compressed file (containing your 100′s of files together). That way you’d only have 1 Save As dialog and the user would only need to unZIP the files.

      Peter

    1. Yes you can do this by removing:
      toolTip=”{FILE_URL}”
      in your button. This will only hide the download link from users but i do not know how secure it is.

      Regards,
      Shaheel

  32. Hi Peter,
    Thanks for this and your many other good examples.
    I have a very basic question.
    Is it possible to have a single button that will offer the user the choice to Save or Open the given file?
    It seems this is a frequent way that files are offered in Windows.
    –Henry

  33. I can not seem to get the fileRef. download() method to work whith in a resultevent. I have a remote call that reurns a file in a url string. I can open the url out side of my application but I can not doenload the file. The fileReference does not seem to work with in a result event. Has anybody ever come accross this?

  34. Hi,, I tested this example.. it worked nice :) . I wonder, how big must be the files to be downloaded by flex.. for example, it is posible to handle a file igger than 4 Gb. ?

    MArco

  35. Hi, is there any way to get it to work with a file URI? eg: file://///123.45.56.789/xxx/yyy/myFile.doc ?
    I tried it a few different ways but I got a few different errors, such as the security sandbox error or that the remote URL protocol must be HTTP or HTTPS…. Any help would be appreciated. Thanks in advance!

  36. Hi!

    Do you know if Is there any way in flex4 to directly open the downloaded file (a byte[]), but without using navigateURL?

    thank you!!

  37. Peter, congratulations, I´m trying to use something similar, I would like to save the modifications in DataGrid in the loaded xml thru FileReference, below the functions, when I try to save the local xml is not saving the changes that the user make on function “texto_painel_change”, I really dont know how to transfer the content typed in the function “item_click” to the function “salvar_xml_click”, if you please could give a hand:

    abrir_topico.addEventListener(MouseEvent.MOUSE_DOWN, procurar_topico);
    function procurar_topico(e:Event)
    {
    file = new FileReference();
    file.addEventListener(Event.SELECT,completou_topico);
    var docFilter:FileFilter = new FileFilter(“Documents”,”topico*.xml”);
    file.browse([docFilter]);
    }
    function completou_topico(e:Event)
    {
    file.addEventListener(Event.COMPLETE, carrega_topico);
    file.load();
    }

    function carrega_topico(e:Event)
    {
    xml = new XML(e.target.data);
    myGrid.dataProvider = new DataProvider();
    for(var i=0;i<xml.telas.tela.length();i++)
    {
    myGrid.addItem({label:xml.telas.tela.texto[i]});
    }
    }
    salvar_xml.addEventListener(MouseEvent.MOUSE_DOWN, salvar_xml_click)
    function salvar_xml_click(e:MouseEvent):void
    {
    var file:FileReference = new FileReference();
    file.save(xml,”.xml”);
    texto_painel.htmlText;
    FileFilter(“Documents”,”*.xml”);
    }

    myGrid.addEventListener(MouseEvent.CLICK, item_click)
    function item_click(e:Event):void
    {
    texto_painel.htmlText = myGrid.selectedItem.label;
    }

    texto_painel.addEventListener(Event.CHANGE, texto_painel_change)
    function texto_painel_change(e:Event):void
    {
    myGrid.selectedItem.label = texto_painel.htmlText;
    }

Comments are closed.