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();
}

2 comments:

Darla said...

Good post.

Bryson said...

Thanks, this was quite useful for me.