28
Jul
07

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.


25 Responses to “Downloading files in Flex using the FileReference class”


  1. 1 Zed Sep 25th, 2007 at 8:04 pm

    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. 2 Gilles TASSE Oct 30th, 2007 at 4:17 am

    Perfect as usual. Those days, it is the most useful site for Flex dev.

  3. 3 theLoggerGuy Dec 6th, 2007 at 8:16 pm

    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.

  4. 4 peterd Dec 6th, 2007 at 9:10 pm

    theLoggerGuy,

    Oh, I’m sure the documentation is correct. According to the Flex 3 beta documentation for the FileReference httpStatus event, it seems that the httpStatus event is only used for uploads and not downloads. Heck, even in my previous example above, I don’t think it is dispatching.

    Peter

  5. 5 Pete Wilson Mar 12th, 2008 at 10:44 am

    Thanks a lot, very useful script, that is exactly what i was looking for! Now if only i could learn to program things like this by myself haha :)

  6. 6 MArcio Mar 24th, 2008 at 12:47 pm

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

  7. 7 MArcio Mar 24th, 2008 at 4:47 pm

    I see to resolve this i’m using

    fileRef.download(urlReq, "teste.txt");// Begin download.
    
  8. 8 Eric V May 25th, 2008 at 7:03 pm

    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?

  9. 9 Ababa May 30th, 2008 at 8:09 am
    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);
    }
    

    :-)

  10. 10 Melvin Jul 8th, 2008 at 9:25 pm

    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!

  11. 11 sandrokan Aug 5th, 2008 at 2:45 pm

    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

  12. 12 peterd Aug 5th, 2008 at 5:59 pm

    sandrokan,

    Can you please file a bug in the public Flash Player bugbase at https://bugs.adobe.com/flashplayer/ ?
    Also, if you post the bug number here, a few of us can vote/watch the issue.

    Thanks,
    Peter

  13. 13 Toll Aug 11th, 2008 at 1:17 am

    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?

  14. 14 Toll Aug 11th, 2008 at 4:29 am

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

  15. 15 Adil Sep 3rd, 2008 at 3:32 am

    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

  16. 16 peterd Sep 3rd, 2008 at 7:14 am

    adil,

    Can you please file a bug at http://bugs.adobe.com/flashplayer/ and include any relevant code/steps to reproduce the issue.

    Thanks,
    Peter

  17. 17 Josh Sep 3rd, 2008 at 9:10 am

    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

  18. 18 bhargavi Sep 25th, 2008 at 9:27 pm

    Hi , thanks for the exapmle .one request can we open a file after downloading .

  19. 19 peterd Sep 26th, 2008 at 12:19 am

    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

  20. 20 DSXP Oct 7th, 2008 at 12:04 pm

    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

  21. 21 gino8080 Oct 10th, 2008 at 5:16 am

    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!

  22. 22 Eric Oct 16th, 2008 at 8:26 pm

    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

  23. 23 Adobe Flex Tutorial Nov 16th, 2008 at 10:24 am

    @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

  24. 24 Saji Nov 16th, 2008 at 9:12 pm

    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

  25. 25 Shobhit Nov 19th, 2008 at 4:08 am

    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.

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




July 2007
M T W T F S S
    Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Badge Farm

  • Firefox 2
  • Powered by Redoable 1.2
  • Feeds burnt by Feedburner
  • Feed