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 when I tried to save it. And it is really hard to google for help on this issue.
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 when I tried to save it. And it is really hard to google for help on this issue.
I used seanalltogether's answer, and wrote this class to handle file downloading.
It is pretty simple. create a
var downloader = new FileDownloader("url", "Local/Path");
and calldownloader.load()
to start downloading.It also supports setting a function to be called when done, and at points while downloading. Passing the onProgress function the number of bytes that have been downloaded. ( I could not figure out how to get a fraction, since I could not figure out how to query the size of the file before it was downloaded)
You want to choose from 2 api combos to accomplish this.
Version 1 is URLLoader and FileStream
Using this combination of class, you would load the file from your server in to air via the URLLoader object. This will download the file in to memory and then notify you when the download is complete. Make sure you initiate the download with a dataFormat of URLLoaderDataFormat.BINARY. You would then initiate a Filestream object and write it out to the disk using writeBytes().
Version 2 is URLStream and FileStream
URLStream is very similar to URLLoader, but instead of waiting for the file to completely download before using the result, data is made available to you during the download. This method works well for large files because you don't have to wait for the full download to start saving it to disk, and you also save on memory since once the player hands it off to you it can release the memory related to that data. YOu would use filestream in exactly the same way, you would just end up doing a writeBytes() on each chunk of the file as it streams in.
Please also check the URLLoader class for downloading files. An excellent example is here: http://www.adobe.com/devnet/air/flex/articles/exploring_file_capabilities.html
This worked out to be very fast for me, as compared to the URLStream class, which was taking ages, and a lot of CPU to download files.
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):
Note: This solution uses Prototype, and AIRAliases.js.
Check out the
flash.net.URLRequest
class which will help you to download the file.