Rodiq » Page 'Download button in flex3'

Download button in flex3

I needed a button that once clicked will allow saving as file a service response, containing an xml with serialized objects (using xstream).

I found two options, both using FileReference object:

- the save method, but works only compiled for flash player 10

http://blog.flexexamples.com/2008/08/25/saving-files-locally-using-the-filereference-classs-save-method-in-flash-player-10/

- the download method, which was also more direct solution

The first problem, finding the absolute url to download:

protected function getAbsolutePath():String {

//crtUrl is relative to the current swf

var crtUrl:String = this.loaderInfo.url as String;

var modulePrefix:String = “com/mypackage”;

var  index:int = crtUrl.indexOf(modulePrefix);

var absolutePath:String = crtUrl.substring(0, index);

return absolutePath;

}

Second, the download code:

<mx:Button label=”export” click=”onExport(event)”/>

//must be declared outside onExport handler!
protected var fileReference:FileReference = new FileReference();

private function onExport(event:Event):void {
var absolutePath:String = getAbsolutePath();

var request:String = absolutePath + “myapp?some_parameter=a_value”;
trace(“request=”+request);
fileReference.download(new URLRequest(request), “export.xml”);
}

The second trick here: my download worked only with fileReference declared globally (so that it’s reference exists after the onExport is run)

Share and Enjoy:
  • Digg
  • StumbleUpon
  • Facebook
  • Google Bookmarks
  • Reddit
  • RSS

Leave a comment


+ two = 8