Its quite hard to believe that such a simple thing – download a file from server in flex is such a pain!
The code was very simple, from the manual and example:
var fileRef:FileReference = new FileReference(); fileRef.download(new URLRequest("myFile.txt"), "myFile.txt");
But in real world, there are things that they didn’t tell unless you hit it!
From flash player 10, all uploads/downloads in fileRef won’t allowed seamlessly. It require user to click a button or hotkey to invoke upload/download action. Otherwise it will give you an error #2167. This isn’t difficult to resolve if it’s not too much of a pain for your user to click a button one more time.
Alert.show("Click OK to download.",null,4,null,startDownload); function startDownload():void{ var fileRef:FileReference; fileRef = new FileReference(); const FILE_URL:String = "myTextFile.txt"; urlReq = new URLRequest(FILE_URL); urlReq.method = URLRequestMethod.GET; try { fileRef.download(urlReq); } catch (error:Error) { Alert.show(error.message); } } }
I thought this could work, not until I found that my previous post… you need to define the fileReference outside of the function… otherwise it won’t!
Finally… this would work:
var fileRef:FileReference; fileRef = new FileReference(); Alert.show("Click OK to download.",null,4,null,startDownload); function startDownload():void{ const FILE_URL:String = "myTextFile.txt"; urlReq = new URLRequest(FILE_URL); urlReq.method = URLRequestMethod.GET; try { fileRef.download(urlReq); } catch (error:Error) { Alert.show(error.message); } }

