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.




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!
Perfect as usual. Those days, it is the most useful site for Flex dev.
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.
theLoggerGuy,
Oh, I’m sure the documentation is correct. According to the Flex 3 beta documentation for the FileReference
httpStatusevent, it seems that thehttpStatusevent is only used for uploads and not downloads. Heck, even in my previous example above, I don’t think it is dispatching.Peter
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 :)
It´s possible update name of file to download
For example i set in my var to
is set to default file name to download file.cfm
It´s possible Auto-update name to teste.txt ??
I see to resolve this i’m using
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?
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); }:-)
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!
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
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
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?
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.?
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
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
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
Hi , thanks for the exapmle .one request can we open a file after downloading .
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
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
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!
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
@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
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
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.