14
Jan
09

Adobe AIR 1.5 DownloadManager API - download files from web / server to your local drive

I wrote couple of handy classes to handle retrieving / downloading of any type of files to a local directory in AIR. These classes are useful for building an AIR application that works online and offline. You can download multimedia, HTML and other file types. Once files are downloaded you can store the information in SQLite database and serve the information, once your system is not connected to the internet.

The core class “DownloadManager.as” allows you to download files to any location in your local drive using: “File.desktopDirectory.resolvePath(fileLocalLocation)” or you can also point to where the application directory sits: “File.applicationStorageDirectory.resolvePath(fileLocalLocation);”


		public function downloadFileFromServer(fileURL:String, fileLocalLocation:String):void
		{
			//var file:File = File.desktopDirectory.resolvePath(fileLocalLocation);
			var file:File = File.applicationStorageDirectory.resolvePath(fileLocalLocation);
			request = new URLRequest(fileURL);
	        fileStream.openAsync(file, FileMode.WRITE);

	        stream.addEventListener(ProgressEvent.PROGRESS, onDownloadProgress);
	        stream.addEventListener(Event.COMPLETE, onDownloadComplete);

	        stream.load(request);
		}

Notice we defined the steam event handlers and load the file. We now need to define event handler, to handle the progess during the download and once completed;


        private function onDownloadProgress(event:ProgressEvent):void
        {
            var byteArray:ByteArray = new ByteArray();
            var precent:Number = Math.round(bytesLoaded*100/bytesTotal);

            bytesLoaded = event.bytesLoaded;
            bytesTotal = event.bytesTotal;

            stream.readBytes(byteArray, 0, stream.bytesAvailable);
            fileStream.writeBytes(byteArray, 0, byteArray.length);

			var progressEvent:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS);
			progressEvent.bytesLoaded = bytesLoaded;
			progressEvent.bytesTotal = bytesTotal;

			this.dispatchEvent(progressEvent);
    	}

    	private function onDownloadComplete(event:Event):void
    	{
            fileStream.close();
            stream.close(); 

            stream.removeEventListener(ProgressEvent.PROGRESS, onDownloadProgress);
            stream.removeEventListener(Event.COMPLETE, onDownloadComplete);

			var completeEvent:Event = new Event(Event.COMPLETE);
			this.dispatchEvent(completeEvent);
    	}

Here’s a little MXML component that implements the download manager and the ReadDirectoryHelper.
Once we init the application, we check if the file exists and download the file if it doesn’t exists. Additionally, we are using the download manager with a ProgressBar to show the download progress.


<WindowedApplication xmlns="http://ns.adobe.com/mxml/2009"
	layout="absolute"
	initialize="init()">

	<Script>
		<![CDATA[
			import com.elad.framework.utils.ReadDirectoryHelper;
			import com.elad.framework.utils.DownloadManager;
			import mx.controls.Alert;

			private function init():void
			{
				var array:Array = ReadDirectoryHelper.getDirectoryFiles("/Users/elad/Desktop/tmp/");
				var isExists:Boolean = ReadDirectoryHelper.isFileExists(array, "file.flv");

				if (isExists == false)
					downloadFile();
				else
					Alert.show("File Already exists");
			}

			private function downloadFile():void
			{
		        var downloadHelper:DownloadManager = new DownloadManager();

		        downloadHelper.addEventListener(ProgressEvent.PROGRESS, onDownloadProgress);
		        downloadHelper.addEventListener(Event.COMPLETE, onDownloadComplete);
		        downloadHelper.downloadFileFromServer("http://samples.mplayerhq.hu/FLV/asian-commercials-are-weird.flv",
		        "/Users/elad/Desktop/tmp/file.flv");
			}

	        private function onDownloadProgress(event:ProgressEvent):void
	        {
                var value:Number = event.bytesLoaded;
                var total:Number = event.bytesTotal;
                var precent:Number = Math.round(value*100/total);

				if (progressBar.minimum==0)
				{
					progressBar.minimum = value;
					progressBar.maximum = total;
				}

				progressBar.label = "Progress "+precent+"%";
                progressBar.setProgress(value, total);
        	}

        	private function onDownloadComplete(event:Event):void
        	{
 				Alert.show("Download Completed!");
        	}

		]]>
	</Script>

	<ProgressBar id="progressBar"
		x="4" y="63"
		minimum="0"
		label="Progress 0%"
		mode="manual" />

</WindowedApplication>

Download Files from Web to local drive Adobe AIR

To download the source code of the AIR application click here.


27 Responses to “Adobe AIR 1.5 DownloadManager API - download files from web / server to your local drive”


  1. 1 Dan Jan 28th, 2009 at 1:21 pm

    Just what I was looking for! Thanks!!!

  2. 2 Arpit Feb 4th, 2009 at 12:26 am

    Hi Elad,

    Thanks for this wonderful API.
    I was looking for calculating disk space availability with my Adobe AIR application. Can you please give me an idea how I can do this??

  3. 3 GenaS Feb 26th, 2009 at 10:57 am

    Hello Elad,

    Thanks for useful example,
    I think about download speed limit,
    How it implement on air, not on server side?

  4. 4 Darren Mar 14th, 2009 at 11:01 pm

    Now if only there was a way that you could launch these files in a non-OS specific manner… Here’s hoping something like this exists in 2.0.

  5. 5 Bruno Brandão Mar 19th, 2009 at 11:14 pm

    Hi man,

    It’s nice solution, but i need to check the CRC of FILE after download, to know if the file downloaded are OK. It’s possible do you guess?

    Thanks,
    Bruno Brandão
    From Brazil

  6. 6 Mohamed Apr 22nd, 2009 at 9:12 am

    Hi all
    Can any one tell me how can i access a pdf file from adobe air [flex] to invoke some actions on it and send to it an variable.
    also i want when i press a button on the pdf file send a variable to adobe air[flex]
    thanks in advance

  7. 7 Paul Apr 22nd, 2009 at 6:58 pm

    Thank you

  8. 8 elad.ny Apr 25th, 2009 at 10:21 am

    In response to GenaS. I am not sure what you are trying to download. In regards to video/audio I think that the best approach to limit the download speed is to use NetStream and limit the buffer size. With FMS you can check the user’s bandwidth connection and set a policy as well as change the buffer dynamically while playing the files.

    In response to Darren: you have the bytes so you can access the file to check it’s integrity.

  9. 9 saurin May 20th, 2009 at 2:36 am

    please me

    i was using this control in for loop means multiple file upload from server .

    that time it is not work properly

    please give me help

  10. 10 elad.ny May 20th, 2009 at 6:47 am

    saurin: the API wasn’t built to support multiple uploads, you can change the API to support that or listen to a Event.COMPLETE and start a new upload.

  11. 11 VPS Jun 6th, 2009 at 10:37 am

    Thank you very muchhhhhh

  12. 12 vin Jul 13th, 2009 at 2:10 am

    this code is really helpful……….
    but i want to ask that ,here u have mentioned .flv format videos .
    I could not use the same code for swf files.
    How can I do this?

  13. 13 elad.ny Jul 19th, 2009 at 5:50 pm

    Hi Vin, you can use this API to download any type of file format. Once the file is downloaded you still needs to load the file and after loaded use the SWF as a sub-application in your main application. It can be done using the SWFObject class (easier but it will load the data again) or you can create a custom class to use the data downloaded and create a sub-application (recommended but require more effort).

  14. 14 avi Jul 22nd, 2009 at 8:11 am

    hi!!!!!!!!
    Plz, can u give me the code for downloading and playing video files(.swf format and around 100 in number) in video player for flex builder3.

    Also, can such application be made(in AIR and Flex builder3) for completely offline use i.e we are storing videos directly in database(no downloading from server) and retrieving and playing in video player in offline mode .

  15. 15 elad.ny Jul 22nd, 2009 at 9:35 am

    Hi Avi, my team and I can definitely help you with your project. Please send me an email through the site form: http://elromdesign.com/?page=contact.

  16. 16 driver87 Oct 22nd, 2009 at 4:07 am

    Thank you all very, very much! ,

  17. 17 Kyle Nov 2nd, 2009 at 10:46 am

    Elad,
    Thanks for the utility! Is there any way to pause and restart a download? Or re-start a broken download? I am using it to download files > 5Gb.

    Kyle

  18. 18 domain kaydi Dec 30th, 2009 at 2:44 am

    thank you for this article. Ive looked at the end.

  19. 19 madhu Dec 31st, 2009 at 1:53 am

    Thanks a million, I am working on this for a day and couldn’t solved it. You helped me a lot.

    One change I did in code is in the class “ReadDirectoryHelper”
    for getting file name you are splitting the path

    file = fileCollection[i] as File;
    fileSplit = file.nativePath.split(File.separator);
    fileName = fileSplit[fileSplit.length-1] as String;

    I think no need to split it as we get file name directly from the file object.
    fileName = file.name

    Thank you,
    Madhu P

  20. 20 IdeasMX Jan 21st, 2010 at 12:47 pm

    Thanks for the code, it will be usefull for one of my projects

  21. 21 Kat Jan 25th, 2010 at 8:25 am

    I looked for something like this forever! Thanks!

  22. 22 Gavri Feb 9th, 2010 at 3:54 pm

    Hi,

    very useful info.

    one question though: lets say I’m saving the bytearray of my loaded file and appending to it on each progress event - now lets say that from some reason the connection is lost.

    can i start downloading the remote file from the place I stopped (passing the ByteArray current positon as an argument)?

    something like URLStream.load() function with an offset arguemet

    Thanks

    gavri

  23. 23 elad.ny Feb 10th, 2010 at 1:20 pm

    Hi Gavri, the API wasn’t built to accommodate what you are trying to do. Streaming and some of the new HTTP streaming allows you to start at a certain point.

  24. 24 GOUTAM NANDI Jun 22nd, 2010 at 7:44 am

    i want to douwnload the adobe air.

  25. 25 Anonymous Jul 11th, 2010 at 11:39 pm

    jk

  26. 26 john Jul 19th, 2010 at 10:01 am

    thanks very much

  1. 1 Adobe AIR Downloader app | Imbimp.com Pingback on Jun 22nd, 2009 at 7:47 am