How do I download a file from the internet in a Flex based AIR application.
I tried using a file with url set to the address, but I got a file does not exist error
To build on seanalltogether's second idea, here is a function that should download a file from the internet, and save it to disk (in the specified file name on the desktop):
downloadFile: function (url, fileName) {
var urlStream = new air.URLStream();
var request = new air.URLRequest(url);
var fileStream = new air.FileStream();
// write 50k from the urlstream to the filestream, unless
// the writeAll flag is true, when you write everything in the buffer
function writeFile(writeAll) {
if (urlStream.bytesAvailable > 51200 || writeAll) {
alert("got some");
var dataBuffer = new air.ByteArray();
urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
}
// do clean up:
if (writeAll) {
alert("done");
fileStream.close();
urlStream.close();
// set up the next download
setTimeout(this.downloadNextFile.bind(this), 0);
}
}
urlStream.addEventListener(air.Event.COMPLETE, writeFile.bind(this, true));
urlStream.addEventListener(air.ProgressEvent.PROGRESS, writeFile.bind(this, false));
var file = air.File.desktopDirectory.resolvePath(fileName);
fileStream.openAsync(file, air.FileMode.WRITE);
urlStream.load(request);
}
Note: This solution uses Prototype, and AIRAliases.js.