2008-08-04

Download a file from a server with AIR

Been working allot in AIR lately and I just got to the point of adding a feature where a user can download a file from the server. Initially I thought the following simple code would do it:

var req:URLRequest = new URLRequest( "http://localhost:8080/orion/pdfdown" );
req.method = URLRequestMethod.POST;
var f:File = new File();
f.download( req, "bla.pdf" );

However running the application with that causes the following error to be thrown: Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error. I really don't understand and after some searching I couldn't find the answer, so I decided to post on Flexcoders, and thanks to Ryan Gravener for posting the solution. In AIR you should use the URLStream class to download files from the server. Like so:

var req:URLRequest = new URLRequest(url);
stream = new URLStream();
stream.addEventListener(Event.COMPLETE, writeAirFile);
stream.load(req);

private function writeAirFile(evt:Event):void {
var data:ByteArray = new ByteArray();
stream.readBytes(fileData,0,stream.bytesAvailable);
var file:File = File.documentsDirectory.resolvePath("bla.pdf");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes(fileData,0,fileData.length);
fileStream.close();
}

7 comments:

Anonymous said...

Good post.

Anonymous said...

Thanks, this was quite useful for me.

Unknown said...

Thanks, good post, I was looking for the way to do it.
Just a little bug now that i test it, it should be:

var fileData:ByteArray = new ByteArray();

Anonymous said...

Can we detect the url of the clicked link?

I want to force download 1 file clicking on url.

Pls heml

Karim Nas said...

great article! thanks!

Anonymous said...

To be a adroit benign being is to procure a amiable of openness to the world, an cleverness to group undeterminable things beyond your own control, that can take you to be shattered in unequivocally outermost circumstances on which you were not to blame. That says something exceedingly impressive relating to the prerequisite of the righteous autobiography: that it is based on a trust in the fitful and on a willingness to be exposed; it's based on being more like a plant than like a prize, something rather dainty, but whose mere precise beauty is inseparable from that fragility.

yanmaneee said...

balenciaga speed
goyard handbags
michael kors purses
jordan shoes
nike 270
lebron 16
air max
cheap jordans
jordan 1 off white
golden goose sneakers