logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
top
Jul 15, 2011 Posted on Jul 15, 2011 in Hints and Tips | 0 comments

Quick Tip: Download Files Via SWFs Using FileReference

This Quick Tip covers how to use AS3′s FileReference class in order to download and save external files from Flash RIAs without the need for server side scripts like PHP. All we need is the path of the file that we want to let the user download.


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Create a New ActionScript 3.0 File

Create a new .fla file and save it into your project folder.

new .fla file

Step 2: Prepare the UI

For this Quick Tip, I created an interface. You can download it from the link at the top of the page or you can create your own.

In my .fla file, there are three images which represent the file types, and three download buttons which are MovieClip Objects

  • btn_img_download for the miki-monk.jpg file
  • btn_mp3_download for the some-audio.mp3 file
  • btn_txt_download for the dummy-text.rtf file

and a progress bar at the bottom to track the download progress placed on the Stage.

interface of the Flash swf file

Step 3: Create Document Class

We will write our code into a Document Class file. If you are not familiar with Document Class, you can get related information from another ActiveTuts+ Quick Tip.

Let’s create our Document Class file; click File>New then select “ActionScript 3.0 Class. Save the AS file into the same location as your .fla file.

Create Document Class File

Link your .fla file to the Action Script File that you created — simply write the name of your AS file into the related field in your .fla file.

Document Class

Step 4: Using FileReference() in Our Code

Here is the Document Class that I used in this Quick Tip. Please read the comments in the code to understand the class behavior.

package
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.events.Event;

	public class FileRefTut extends Sprite
	{
		//Download Buttons at the Stage.We have to define them as public variables in our Document Class in order to use them.
		//Otherwise, we get error message from Flash.
		public var btn_img_download : MovieClip,
		           btn_txt_download : MovieClip,
		           btn_mp3_download : MovieClip,
		           mc_loaded        : MovieClip;

		//Progress Bar
		public var mc_progress : MovieClip,
		//Dynamic TextField stays under the Progress Bar.
				   txt_prog    : TextField;

		//Arr_Links hold the list of files.
		private var Arr_Links  : Array;

		//Default Path where the download is stored.
		//You change it according to your setup.
		//This is relative to the SWF.
		private var defaultPath : String = "assets/";

		//File Name
		private var urlName : String;

		//instance of FileReference() Class
		private var fr : FileReference;

		//url of the requested files
		private var req : URLRequest;

		public function FileRefTut() : void
		{
			//Set buttonMode to true to change mouse curser to hand icon
			btn_img_download.buttonMode = btn_txt_download.buttonMode = btn_mp3_download.buttonMode = true;

			//Set width of the mc_loaded progress bar to 0 when there isn't any downloading
			mc_loaded.scaleX = 0;

			//Create list of files to be downloaded
			//These files must be in the folder specified by defaultPath
			Arr_Links = ["miki-monk.jpg","some-audio.mp3","dummy-text.rtf"];

			//Create a request object
			req = new URLRequest();

			//Create an instance of the FileReference Class
			fr = new FileReference();

			//ProgressEvent to scale Progress Bar
			//We need to add ProgressEvent Listener based on the progress of FileReference
			fr.addEventListener( ProgressEvent.PROGRESS,progressHandler );

			//Use COMPLETE Event to determine when the download has finished
			fr.addEventListener( Event.COMPLETE,completeHandler );

			//Event Listeners for Download Buttons
			//When user clicks any download button, call downloadFile(e:MouseEvent) function
			btn_img_download.addEventListener( MouseEvent.CLICK,downloadFile );
			btn_mp3_download.addEventListener( MouseEvent.CLICK,downloadFile );
			btn_txt_download.addEventListener( MouseEvent.CLICK,downloadFile );

		}

		private function downloadFile( e : MouseEvent ) : void
		{
			//set the download path to the urlName variable according to clicked Download Button
			switch (e.target.name)
			{
				case "btn_img_download":
				urlName = Arr_Links[0];
				break;

				case "btn_mp3_download":
				urlName = Arr_Links[1];
				break;

				case "btn_txt_download":
				urlName = Arr_Links[2];
				break;
			}

			//change text message "progress" to "downloading..." at txt_prog Dynamic TextFiled
			txt_prog.text = "downloading...";

			//Assign url to the req variable
			req.url = defaultPath + urlName;

			//Downlaod requested file
			fr.download( req );
		}

		private function progressHandler( event : ProgressEvent ) : void
		{
			//We scale the progress bar according to ration of (event.bytesLoaded / event.bytesTotal)
			//So, when scaleX reaches 1, it means the download is finished..
			mc_loaded.scaleX = (event.bytesLoaded / event.bytesTotal) ;
		}

		private function completeHandler( event : Event ) : void
		{
			//reset progress bar to 0 after download is finished
			mc_loaded.scaleX = 0;

			//change text message
			txt_prog.text = "download finished";
		}
	}
}

As you can see the key is to use FileReference with a URLRequest, to enable downloading files from our server. Basically we need 3 things:

  1. Create an instance of FileReference Class
  2. private var fr : FileReference;
    
  3. Create an instance of URLRequest Class
  4. private var req : URLRequest;
    
  5. Assign the file path to the url parameter of URLRequest instance and call download method of FileReference Class
  6. req.url = defaultPath + urlName;
    fr.download( req );
    

Note: If you want to download files from another host, you have to put a crossdomain.xml file into that host. Let’s say, you put your swf file into www.host-a.com, and you want to download files from www.host-b.com with your swf file in www.host-a.com. To do that, you need permisson from www.host-b.com. So, you have to upload a crossdomain.xml file into www.host-b.com. If you wawnt learn more about crossdomain.xml files, there is another nice Quick Tip here.


Conclusion

In this Quick Tip, we learned how to download files from a server, via Flash, to the local system without any need for server side scripts like PHP. Hope you like this Quick Tip and thank you for reading it. If you have any questions, please drop a comment below.



View full post on Activetuts+

banner ad

Leave a Reply

Click here to cancel reply.

search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
  • Quick Tip: Versioning Your Files With Dropbox (via Webdesigntuts+)
  • Workshop: Nuclear Outrun – Critique
  • Understanding Variables, Arrays, Loops, and Null: The Post-it Note Analogy
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Tween Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting