Download files in Flex
Download the file is very simple, using this filereference class can be, 3 lines of code can, in the experiment found no response, in repeated testing finally found the reason.
Downloading files in Flex is asynchronous, and you have to set the lifetime of the Filereference class to a longer period of time.
Here's the code.
<?xml version= "1.0" encoding= "Utf-8"?>
<mx:application xmlns:mx= "Http://www.adobe.com/2006/mxml" layout= "absolute" backgroundcolor= "#f6f6f6" Backgroundgradientcolors= "[#f6f6f6, #bbbbbb]" >
<mx:label x= "y=" text= "Download File" fontsize= "fontweight=" "bold"/>
<mx:hrule x= "y=" width= "80%"/>
<mx:button x= "y=" label= "Download HTML Component" click= "{Download ()}"/>
<mx:Script>
<! [cdata[
private Var downloadurl:urlrequest;
private Var file:filereference; It's going to be the main place
Public function Download (): void {
DownloadURL = new URLRequest ("Http://localhost/flex/1.html.bak");
File = new Filereference ();
Configurelisteners (file);
File.download (DownloadURL);
}
Private Function Configurelisteners (dispatcher:ieventdispatcher): void {
Dispatcher.addeventlistener (Event.cancel, Cancelhandler);
Dispatcher.addeventlistener (Event.complete, Completehandler);
Dispatcher.addeventlistener (Ioerrorevent.io_error, Ioerrorhandler);
Dispatcher.addeventlistener (Event.open, Openhandler);
Dispatcher.addeventlistener (progressevent.progress, Progresshandler);
Dispatcher.addeventlistener (Securityerrorevent.security_error, Securityerrorhandler);
Dispatcher.addeventlistener (Event.select, Selecthandler);
}
Private Function Cancelhandler (event:event): void {
Trace ("Cancelhandler:" + event);
}
Private Function Completehandler (event:event): void {
Trace ("Completehandler:" + event);
}
Private Function Ioerrorhandler (event:ioerrorevent): void {
Trace ("Ioerrorhandler:" + event);
}
Private Function Openhandler (event:event): void {
Trace ("Openhandler:" + event);
}
Private Function Progresshandler (event:progressevent): void {
var file:filereference = filereference (event.target);
Trace ("Progresshandler name=" + file.name + "bytesloaded=" + event.bytesloaded + "bytestotal=" + event.bytestotal);
}
Private Function Securityerrorhandler (event:securityerrorevent): void {
Trace ("Securityerrorhandler:" + event);
}
Private Function Selecthandler (event:event): void {
var file:filereference = filereference (event.target);
Trace ("selecthandler:name=" + file.name + "url=" + downloadurl.url);
}
]]>
</mx:Script>
</mx:Application>
But remember to open your own server and put the downloaded files up.