O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Downloading Files

Problem

You want to let users download files to their computer.

Solution

Use the download() method of a FileReference object.

Discussion

The flash.net.FileReference class defines a download() method that allows users to download a file from a URL to their computers. When Flash Player calls the download() method, it attempts to open a dialog box, titled “Select location for download.” This dialog box allows users to use a standard operating system dialog to browse their local disks for a location to which they want to save files.

The first step before calling the download() method is to construct a FileReference object, as follows:

var fileReference:FileReference = new FileReference();

The download() method requires at least one parameter as a URLRequest object, specifying the URL from which you want to download the file. In the simplest case, the URL points to a static file that the user can download. The following example opens a save dialog box that allows users to select a location to which they can save a copy of example.txt from the same directory on the server where the SWF resides:

var urlRequest:URLRequest = new URLRequest("example.txt");
fileReference.download(urlRequest);

Specifying a full path to a file is as simple as specifying the URL when constructing the URLRequest object, as the following example illustrates:

var urlRequest:URLRequest = new URLRequest("http://www.myexamplesite.com/example.txt");
fileReference.download(urlRequest);

The save dialog box also ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required