Monday, May 17, 2010

FileReference.download() don't save the file


Environment:
Flash, Action Script 3 




Scenario:
When creating a FileReference.download()  for downloading a file to user local hard drive the download dialog is open as it should but when I click the "Save" button I can't find the saved file.

Problem:
The FileReference variable is declared inside the download function and as a result of that he is a "local variable" (obviously :-) ).
When the download dialog is opened, the FileReference is unknown since he was declared inside the function. code sample 1

Solution:
Declare the FileReference variable outside the download function as a "Global variable". code sample 2


Code sample 1:

 
 private function startDownload(e:Event):void  
 { 
 var fileRefToDownload:fileRefToDownload = new FileReference(); 
 fileRefToDownload.addEventListener(Event.COMPLETE, downloadCompleted); 
 fileRefToDownload.download(new URLRequest(fileToDownloadURL), "this_is_my_file_name.jpg"); 
 } 



Code sample 2:


var fileRefToDownload:fileRefToDownload; 
  private function startDownload(e:Event):void  
  {  
  fileRefToDownload = new FileReference();  
  fileRefToDownload.addEventListener(Event.COMPLETE, downloadCompleted);  
  fileRefToDownload.download(new URLRequest(fileToDownloadURL), "this_is_my_file_name.jpg");  
  }