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.


12 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

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