A File object represents a path to a file or directory. This can be an existing file or directory, or it can be one that does not yet exist; for instance, it can represent the path to a file or directory that you plan to create.

The File class has a number of properties and methods for getting information about the file system and for performing operations, such as copying files and directories.

You can use File objects along with the FileStream class to read and write files.

The File class extends the FileReference class. The FileReference class represents a pointer to a file, but the File class adds properties and methods that are not exposed in Flash or HTML5.

The File class includes static properties that let you reference commonly used directory locations. These static properties include:

  • File.applicationStorageDirectory—a storage directory unique to each installed application
  • File.applicationDirectory—the read-only directory where the application is installed (along with any installed assets)
  • File.desktopDirectory—the user's desktop directory
  • File.documentsDirectory—the user's documents directory
  • File.userDirectory—the user directory

These properties have meaningful values on different operating systems. For example, Mac OS, Linux, and Windows each have different native paths to the user's desktop directory. However, the File.desktopDirectory property points to the correct desktop directory path on each of these platforms. To write applications that work well across platforms, use these properties as the basis for referencing other files used by the application. Then use the resolvePath() method to refine the path. For example, this code points to the preferences.xml file in the application storage directory:

	var prefsFile:File = File.applicationStorageDirectory;
	prefsFile = prefsFile.resolvePath("preferences.xml");

If you use a literal native path in referencing a file, it will only work on one platform. For example, the following File object would only work on Windows:

	new File("C:\Documents and Settings\joe\My Documents\test.txt")

The application storage directory is particularly useful. It gives an application-specific storage directory for the AIR application. It is defined by the File.applicationStorageDirectory property.

Events:

cancel

Dispatched when a pending asynchronous operation is canceled.

complete

Dispatched when an asynchronous operation is complete.

directoryListing

Dispatched when a directory list is available as a result of a call to the getDirectoryListingAsync() method.

ioError

Dispatched when an error occurs during an asynchronous file operation.

securityError

Dispatched when an operation violates a security constraint.

select

Dispatched when the user selects a file or directory from a file- or directory-browsing dialog box.

selectMultiple

Dispatched when the user selects files from the dialog box opened by a call to the browseForOpenMultiple() method.

See also:

Static variables

staticread onlyapplicationDirectory:File

The folder containing the application's installed files.

The url property for this object uses the app URL scheme (not the file URL scheme). This means that the url string is specified starting with "app:" (not "file:"). Also, if you create a File object relative to the File.applicationDirectory directory (by using the resolvePath() method), the url property of the File object also uses the app URL scheme. The url property is currently unsupported on all targets execpt AIR.

Note: You cannot write to files or directories that have paths that use the app: URL scheme. Also, you cannot delete or create files or folders that have paths that use the app: URL scheme. Modifying content in the application directory is a bad practice, for security reasons, and is blocked by the operating system on some platforms. If you want to store application-specific data, consider using the application storage directory (File.applicationStorageDirectory). If you want any of the content in the application storage directory to have access to the application-privileged functionality (AIR APIs), you can expose that functionality by using a sandbox bridge.

The applicationDirectory property provides a way to reference the application directory that works across platforms. If you set a File object to reference the application directory using the nativePath or url property, it will only work on the platform for which that path is valid.

On Android, the nativePath property of a File object pointing to the application directory is an empty string. Use the url property to access application files.

staticread onlyapplicationStorageDirectory:File

The application's private storage directory.

Each application has a unique, persistent application storage directory, which is created when you first access File.applicationStorageDirectory. This directory is unique to each application and user. This directory is a convenient location to store user-specific or application-specific data.

The url property for this object uses the app-storage URL scheme (not the file URL scheme). This means that the url string is specified starting with "app-storage:" (not "file:"). Also, if you create a File object relative to the File.applicationStoreDirectory directory (by using the resolvePath() method), the url of the File object also uses the app-storage URL scheme (as in the example). The url property is currently unsupported on all targets execpt AIR.

The applicationStorageDirectory property provides a way to reference the application storage directory that works across platforms. If you set a File object to reference the application storage directory using the nativePath or url property, it will only work on the platform for which that path is valid.

The following code creates a File object pointing to the "images" subdirectory of the application storage directory.

import openfl.filesystem.File;

var tempFiles:File = File.applicationStorageDirectory;
tempFiles = tempFiles.resolvePath("images/");
trace(tempFiles.url); // app-storage:/images

staticread onlydesktopDirectory:File

The user's desktop directory.

The desktopDirectory property provides a way to reference the desktop directory that works across platforms. If you set a File object to reference the desktop directory using the nativePath or url property, it will only work on the platform for which that path is valid.

If an operating system does not support a desktop directory, a suitable directory in the file system is used instead.

The following code outputs a list of files and directories contained in the user's desktop directory.

import openfl.filesystem.File;
var desktop:File = File.desktopDirectory;

var files:Array = desktop.getDirectoryListing();

for (var i:uint = 0; i < files.length; i++) {
	trace(files[i].nativePath);
}

staticread onlydocumentsDirectory:File

The user's documents directory.

On Windows, this is the My Documents directory (for example, C:\Documents and Settings\userName\My Documents). On Mac OS, the default location is /Users/userName/Documents. On Linux, the default location is /home/userName/Documents (on an English system), and the property observes the xdg-user-dirs setting.

The documentsDirectory property provides a way to reference the documents directory that works across platforms. If you set a File object to reference the documents directory using the nativePath or url property, it will only work on the platform for which that path is valid.

If an operating system does not support a documents directory, a suitable directory in the file system is used instead.

The following code uses the File.documentsDirectory property and the File.createDirectory() method to ensure that a directory named "OpenFL Test" exists in the user's documents directory.

import openfl.filesystem.File;

var directory:File = File.documentsDirectory;
directory = directory.resolvePath("OpenFL Test");

File.createDirectory(directory);
trace(directory.exists); // true

staticread onlylineEnding:String

The line-ending character sequence used by the host operating system.

On Mac OS and Linux, this is the line-feed character (character code 0x0A hexadecimal). On Windows, this is the carriage return character (character code 0x0D hexadecimal) followed by the line-feed character (character code 0x0A hexadecimal).

staticread onlyseparator:String

The host operating system's path component separator character.

On Mac OS and Linux, this is the forward slash (/) character. On Windows, it is the backslash (\) character.

Note: When using the backslash character in a String literal, remember to type the character twice (as in "directory\\file.ext"). Each pair of backslashes in a String literal represent a single backslash in the String.

staticread onlyuserDirectory:File

The user's directory.

On Windows, this is the parent of the My Documents directory (for example, C:\Documents and Settings\userName). On Mac OS, it is /Users/userName. On Linux, it is /home/userName.

The userDirectory property provides a way to reference the user directory that works across platforms. If you set the nativePath or url property of a File object directly, it will only work on the platform for which that path is valid.

If an operating system does not support a user directory, a suitable directory in the file system is used instead.

The following code outputs a list of files and directories contained in the root level of the user directory:

import openfl.filesystem.File;

var files:Array = File.userDirectory.listDirectory();
for (var i:uint = 0; i < files.length; i++) {
	trace(files[i].nativePath);
}

Static methods

staticcreateTempDirectory():File

Returns a reference to a new temporary directory. This is a new directory in the system's temporary directory path.

This method lets you identify a new, unique directory, without having to query the system to see that the directory is new and unique.

You may want to delete the temporary directory before closing the application, since on some devices it is not deleted automatically.

Returns:

File A File object referencing the new temporary directory. The following code uses the createTempFile() method to obtain a reference to a new temporary directory.

import openfl.File;
var temp:File = File.createTempDirectory();
trace(temp.nativePath);

Each time you run this code, a new (unique) file is created.

staticcreateTempFile():File

Returns a reference to a new temporary file. This is a new file in the system's temporary directory path.

This method lets you identify a new, unique file, without having to query the system to see that the file is new and unique.

You may want to delete the temporary file before closing the application, since it is not deleted automatically.

Returns:

File A File object referencing the new temporary file; The following code uses the createTempFile() method to obtain a reference to a new temporary file.

import openfl.File;
var temp:File = File.createTempFile();
trace(temp.nativePath);

staticgetRootDirectories():Array<File>

Returns an array of File objects, listing the file system root directories.

For example, on Windows this is a list of volumes such as the C: drive and the D: drive. An empty drive, such as a CD or DVD drive in which no disc is inserted, is not included in this array. On Mac OS and Linux, this method always returns the unique root directory for the machine (the "/" directory)

	On file systems for which the root is not readable, such as the Android file system, the properties of
	the returned File object do not always reflect the true value. For example, on Android, the
	spaceAvailable property reports 0.

	@returns Array An array of File objects, listing the root directories.

	The following code outputs a list of root directories:

	```hx
	import flash.filesystem.File;
	var rootDirs:Array = File.getRootDirectories();

	for (var i:uint = 0; i < rootDirs.length; i++) {
		trace(rootDirs[i].nativePath);
	}
	```

Constructor

@:value({ path : null })new(?path:String)

The constructor function for the File class.

If you pass a path argument, the File object points to the specified path, and the nativePath property and and url property are set to reflect that path.

Although you can pass a path argument to specify a file path, consider whether doing so may result in platform-specific code. For example, a native path such as "C:\Documents and Settings\bob\Desktop" or a URL such as "file:///C:/Documents%20and%20Settings/bob/Desktop" is only valid on Windows. It is far better to use the following static properties, which represent commonly used directories, and which are valid on all platforms:

*File.applicationDirectory
*File.applicationStorageDirectory
*File.desktopDirectory
*File.documentsDirectory
*File.userDirectory

You can then use the resolvePath() method to get a path relative to these directories. For example, the following code sets up a File object to point to the settings.xml file in the application storage directory:

var file:File = File.applicationStorageDirectory.resolvePath("settings.xml");

Parameters:

path

The path to the file. You can specify the path by using either a URL or native path (platform-specific) notation.

Throws:

ArgumentError

The syntax of the path parameter is invalid.

Variables

read onlyexists:Bool

Indicates whether the referenced file or directory exists. The value is true if the File object points to an existing file or directory, false otherwise.

The following code creates a temporary file, then deletes it and uses the File.exists property to check for the existence of the file.

import openfl.filesystem.*;

var temp:File = File.createTempFile();
trace(temp.exists); // true
temp.deleteFile();
trace(temp.exists); // false

@:value(null)read onlyicon:Icon = null

An Icon object containing the icons defined for the file. An Icon object is an array of BitmapData objects corresponding to the various icon states. On Linux, the Icon object contains no icons. On Android, the icon property is null.

read onlyisDirectory:Bool

Indicates whether the reference is to a directory. The value is true if the File object points to a directory; false otherwise.

The following code creates an array of File objects pointing to files and directories in the user directory and then uses the isDirectory property to list only those File objects that point to directories (not to files).

import openfl.filesystem.*;

var userDirFiles:Array = File.userDirectory.getDirectoryListing();
for (var i:uint = 0; i < userDirFiles.length; i++) {
	if (userDirFiles[i].isDirectory) {
		trace(userDirFiles[i].nativePath);
	}
}

read onlyisHidden:Bool

Indicates whether the referenced file or directory is "hidden." The value is true if the referenced file or directory is hidden, false otherwise.

The following code creates an array of File objects pointing to files and directories in the user directory and then uses the isHidden property to list hidden files and directories.

import openfl.filesystem.*;

var userDirFiles:Array = File.userDirectory.getDirectoryListing();
for (var i:uint = 0; i < userDirFiles.length; i++) {
	if (userDirFiles[i].isHidden) {
		trace(userDirFiles[i].nativePath);
	}
}

nativePath:String

The full path in the host operating system representation. On Mac OS and Linux, the forward slash (/) character is used as the path separator. However, in Windows, you can set the nativePath property by using the forward slash character or the backslash () character as the path separator, and AIR automatically replaces forward slashes with the appropriate backslash character.

Before writing code to set the nativePath property directly, consider whether doing so may result in platform-specific code. For example, a native path such as "C:\Documents and Settings\bob\Desktop" is only valid on Windows. It is far better to use the following static properties, which represent commonly used directories, and which are valid on all platforms:

*File.applicationDirectory
*File.applicationStorageDirectory
*File.desktopDirectory
*File.documentsDirectory
*File.userDirectory

You can use the resolvePath() method to get a path relative to these directories.

Throws:

ArgumentError

The syntax of the path is invalid.

SecurityError

The caller is not in the application security sandbox. The following code shows the difference between the nativePath property and the url property of a File object. The comments show results on an example Windows computer.

import openfl.filesystem.File;
var docs:File = File.documentsDirectory;
trace(docs.nativePath); // C:\Documents and Settings\turing\My Documents
trace(docs.url); // file:///C:/Documents%20and%20Settings/turing/My%20Documents

read onlyparent:File

The directory that contains the file or directory referenced by this File object.

If the file or directory does not exist, the parent property still returns the File object that points to the containing directory, even if that directory does not exist.

This property is identical to the return value for resolvePath("..") except that the parent of a root directory is null.

The following code uses the parent property to show the directory that contains a temporary file.

import openfl.filesystem.File;

var tempFile:File = File.createTempDirectory();
trace(tempFile.parent.nativePath);
tempFile.deleteFile();

Methods

@:value({ typeFilter : null })browse(?typeFilter:Array<FileFilter>):Bool

Displays a file-browsing dialog box that lets the user select a file to upload.

browseForDirectory(title:String):Void

Displays a directory chooser dialog box, in which the user can select a directory. When the user selects the directory, the select event is dispatched. The target property of the select event is the File object pointing to the selected directory.

The directory chooser dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Parameters:

title

The string that is displayed in the title bar of the dialog box.

Throws:

IllegalOperationError

A browse operation (browseForOpen(), browseForOpenMultiple(), browseForSave(), browseForDirectory()) is currently running. The following code uses the File.browseForDirectory() method to let the user select a directory. When the directory is selected, the code lists the contents of the selected directory in the trace() output.

import openfl.filesystem.File;
import openfl.events.Event;
var directory:File = File.documentsDirectory;
try
{
	directory.browseForDirectory("Select Directory");
	directory.addEventListener(Event.SELECT, directorySelected);
}
catch (error:Error)
{
	trace("Failed:", error.message);
}
function directorySelected(event:Event):void
{
	directory = event.target as File;
	var files:Array = directory.getDirectoryListing();
	for(var i:uint = 0; i < files.length; i++)
	{
		trace(files[i].name);
	}
}

Events:

cancel

Dispatched when the user clicks the Cancel button in the Open File dialog box.

select

Dispatched when the user selects a directory and closes the directory chooser dialog box.

@:value({ typeFilter : null })browseForOpen(title:String, ?typeFilter:Array<FileFilter>):Void

Displays the Open File dialog box, in which the user can select a file to open.

When the user selects the file, the select event is dispatched. The target property of the select event is the File object pointing to the selected file.

The Open File dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Parameters:

title

The string that is displayed in the title bar of the dialog box.

typeFilter

An array of FileFilter instances used to filter the files that are displayed in the dialog box. If you omit this parameter, all files are displayed. For more information, see the FileFilter class.

Throws:

IllegalOperationError

A browse operation (browseForOpen(), browseForOpenMultiple(), browseForSave(), browseForDirectory()) is currently running.

SecurityError

The application does not have the necessary permissions. The following code uses the File.browseForOpen() method to let the user choose a text file. When the file is selected, the code reads the file data into a string.

import openfl.filesystem.*;
import openfl.events.Event;
import openfl.net.FileFilter;
var fileToOpen:File = new File();
var txtFilter:FileFilter = new FileFilter("Text", "*.as;*.css;*.html;*.txt;*.xml");
try
{
	fileToOpen.browseForOpen("Open", [txtFilter]);
	fileToOpen.addEventListener(Event.SELECT, fileSelected);
}
catch (error:Error)
{
	trace("Failed:", error.message);
}
function fileSelected(event:Event):void
{
	var stream:FileStream = new FileStream();
	stream.open(event.target, FileMode.READ);
	var fileData:String = stream.readUTFBytes(stream.bytesAvailable);
	trace(fileData);
}

Events:

cancel

Dispatched when the user clicks the Cancel button in the Open File dialog box.

select

Dispatched when the user selects a directory and closes the directory chooser dialog box.

@:value({ typeFilter : null })browseForOpenMultiple(title:String, ?typeFilter:Array<FileFilter>):Void

Displays the Open File dialog box, in which the user can select one or more files to open.

When the user selects the files, the selectMultiple event is dispatched. The target property of the select event is this File object. Unlike browseForOpen(), with the browseForOpenMultiple() method, this File object is not updated to reference any of the chosen files. Instead, the resulting selectMultiple event contains an array of the chosen files.

The Open File dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Parameters:

title

The string that is displayed in the title bar of the dialog box.

typeFilter

An array of FileFilter instances used to filter the files that are displayed in the dialog box. If you omit this parameter, all files are displayed. For more information, see the FileFilter class.

Throws:

IllegalOperationError

A browse operation (browseForOpen(), browseForOpenMultiple(), browseForSave(), browseForDirectory()) is currently running.

SecurityError

The application does not have the necessary permissions. The following code uses the File.browseForOpenMultiple() method to let the user choose multiple files. When the files are selected, the code outputs the paths for the selected files.

import openfl.filesystem.*;
import openfl.events.FileListEvent;
var docsDir:File = File.documentsDirectory;
try
{
	docsDir.browseForOpenMultiple("Select Files");
	docsDir.addEventListener(FileListEvent.SELECT_MULTIPLE, filesSelected);
}
catch (error:Error)
{
	trace("Failed:", error.message);
}
function filesSelected(event:FileListEvent):void
{
	for (var i:uint = 0; i < event.files.length; i++)
	{
		trace(event.files[i].nativePath);
	}
}

Events:

cancel

Dispatched when the user clicks the Cancel button in the Open File dialog box.

select

Dispatched when the user selects a directory and closes the directory chooser dialog box.

browseForSave(title:String):Void

Displays the Save File dialog box, in which the user can select a file destination.

When the user selects the file, the select event is dispatched. The target property of the select event is the File object pointing to the selected Save destination.

The Save File dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Parameters:

title

The string that is displayed in the title bar of the dialog box. If you omit this parameter, all files are displayed. For more information, see the FileFilter class.

Throws:

IllegalOperationError

A browse operation (browseForOpen(), browseForOpenMultiple(), browseForSave(), browseForDirectory()) is currently running.

SecurityError

The application does not have the necessary permissions. The following code uses the File.browseForSave() method to let the user select a path for saving a file. When the files are selected, the code saves data to the selected file path.

import openfl.filesystem.*;
import openfl.events.Event;
var docsDir:File = File.documentsDirectory;
try
{
	docsDir.browseForSave("Save As");
	docsDir.addEventListener(Event.SELECT, saveData);
}
catch (error:Error)
{
	trace("Failed:", error.message);
}
function saveData(event:Event):void
{
	var newFile:File = event.target as File;
	var str:String = "Hello.";
	if (!newFile.exists)
	{
		var stream:FileStream = new FileStream();
		stream.open(newFile, FileMode.WRITE);
		stream.writeUTFBytes(str);
		stream.close();
	}
}

Events:

cancel

Dispatched when the user clicks the Cancel button in the Open File dialog box.

select

Dispatched when the user selects a directory and closes the directory chooser dialog box.

cancel():Void

Cancels any pending asynchronous operation.

canonicalize():Void

Canonicalizes the File path.

If the File object represents an existing file or directory, canonicalization adjusts the path so that it matches the case of the actual file or directory name. If the File object is a symbolic link, canonicalization adjusts the path so that it matches the file or directory that the link points to, regardless of whether the file or directory that is pointed to exists. On case sensitive file systems (such as Linux), when multiple files exist with names differing only in case, the canonicalize() method adjusts the path to match the first file found (in an order determined by the file system).

The following code shows how to use the canonicalize() method to find the correct capitalization of a directory name. Before running this example, create a directory named AIR Test on the desktop of your computer.

import openfl.filesystem.*;

var path:File = File.desktopDirectory.resolvePath("air test");
trace(path.nativePath);
path.canonicalize();
trace(path.nativePath); // ...\AIR Test

clone():File

Returns a copy of this File object. Event registrations are not copied.

Note: This method does not copy the file itself. It simply makes a copy of the instance of the Haxe File object. To copy a file, use the copyTo() method.

@:value({ overwrite : false })copyTo(newLocation:FileReference, overwrite:Bool = false):Void

Copies the file or directory at the location specified by this File object to the location specified by the newLocation parameter. The copy process creates any required parent directories (if possible). When overwriting files using copyTo(), the file attributes are also overwritten.

Parameters:

newLocation

The target location of the new file. Note that this File object specifies the resulting (copied) file or directory, not the path to the containing directory.

overwrite

If false, the copy fails if the file specified by the target parameter already exists. If true, the operation overwrites existing file or directory of the same name.

Throws:

IOError

The source does not exist; or the source could not be copied to the target; or the source and destination refer to the same file or folder and overwrite is set to true. On Windows, you cannot copy a file that is open or a directory that contains a file that is open.

SecurityError

The application does not have the necessary permissions. The following code shows how to use the copyTo() method to copy a file. Before running this code, create a test1.txt file in the AIR Test subdirectory of the documents directory on your computer. The resulting copied file is named test2.txt, and it is also in the OpenFL Test subdirectory. When you set the overwrite parameter to true, the operation overwrites any existing test2.txt file.

import openfl.filesystem.File;
import openfl.events.Event;
var sourceFile:FileReference = File.documentsDirectory;
sourceFile = sourceFile.resolvePath("OpenFL Test/test1.txt");
var destination:FileReference = File.documentsDirectory;
destination = destination.resolvePath("OpenFL Test/test2.txt");
if (sourceFile.copyTo(destination, true)) {
	trace("Done.");
}

The following code shows how to use the copyTo() method to copy a file. Before running this code, create a test1.txt file in the OpenFL Test subdirectory of the home directory on your computer. The resulting copied file is named test2.txt. The try and catch statements show how to respond to errors.

import openfl.filesystem.File;
var sourceFile:File = File.documentsDirectory;
sourceFile = sourceFile.resolvePath("OpenFL Test/test1.txt");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("OpenFL Test/test2.txt");
try
{
	sourceFile.copyTo(destination, true);
}
catch (error:Error)
{
	trace("Error:", error.message);
}

@:value({ overwrite : false })copyToAsync(newLocation:FileReference, overwrite:Bool = false):Void

Begins copying the file or directory at the location specified by this File object to the location specified by the destination parameter.

Upon completion, either a complete event (successful) or an ioError event (unsuccessful) is dispatched. The copy process creates any required parent directories (if possible).

Parameters:

newLocation

The target location of the new file. Note that this File object specifies the resulting (copied) file or directory, not the path to the containing directory.

overwrite

If false, the copy fails if the file specified by the target parameter already exists. If true, the operation overwrites existing file or directory of the same name.

Throws:

SecurityError

The application does not have the necessary permissions to write to the destination. The following code shows how to use the copyToAsync() method to copy a file. Before running this code, be sure to create a test1.txt file in the OpenFL Test subdirectory of the documents directory on your computer. The resulting copied file is named test2.txt, and it is also in the AIR Test subdirectory. When you set the overwrite parameter to true, the operation overwrites any existing test2.txt file.

import openfl.filesystem.File;
import openfl.events.Event;
var sourceFile:File = File.documentsDirectory;
sourceFile = sourceFile.resolvePath("OpenFL Test/test1.txt");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("OpenFL Test/test2.txt");
sourceFile.copyToAsync(destination, true);
sourceFile.addEventListener(Event.COMPLETE, fileCopiedHandler);
function fileCopiedHandler(event:Event):void {
	trace("Done.");
}

Events:

complete

Dispatched when the file or directory has been successfully copied.

ioError

The source does not exist; or the source could not be copied to the target; or the source and destination refer to the same file or folder and overwrite is set to true. On Windows, you cannot copy a file that is open or a directory that contains a file that is open.

createDirectory():Void

Creates the specified directory and any necessary parent directories. If the directory already exists, no action is taken.

Throws:

IOError

The directory did not exist and could not be created.

SecurityError

The application does not have the necessary permissions. The following code moves a file named test.txt on the desktop to the OpenFL Test subdirectory of the documents directory. The call to the createDirectory() method ensures that the OpenFL Test directory exists before the file is moved.

import openfl.filesystem.*;
var source:File = File.desktopDirectory.resolvePath("test.txt");
var target:File = File.documentsDirectory.resolvePath("OpenFL Test/test.txt");
var targetParent:File = target.parent;
targetParent.createDirectory();
source.moveTo(target, true);

@:value({ deleteDirectoryContents : false })deleteDirectory(deleteDirectoryContents:Bool = false):Void

Deletes the directory.

Parameters:

deleteDirectoryContents

Specifies whether or not to delete a directory that contains files or subdirectories. When false, if the directory contains files or directories, a call to this method throws an exception.

Throws:

IOError

The directory does not exist, or the directory could not be deleted. On Windows, you cannot delete a directory that contains a file that is open.

SecurityError

The application does not have the necessary permissions to delete the directory. The following code creates an empty directory and then uses the deleteDirectory() method to delete the directory.

import openfl.filesystem.File;
var directory:File = File.documentsDirectory.resolvePath("Empty Junk Directory/");
File.createDirectory(directory);
trace(directory.exists); // true
directory.deleteDirectory();
trace(directory.exists); // false

@:value({ deleteDirectoryContents : false })deleteDirectoryAsync(deleteDirectoryContents:Bool = false):Void

Deletes the directory asynchronously.

@events complete Dispatched when the directory has been deleted successfully. @events ioError The directory does not exist or could not be deleted. On Windows, you cannot delete a directory that contains a file that is open.

Parameters:

deleteDirectoryContents

Specifies whether or not to delete a directory that contains files or subdirectories. When false, if the directory contains files or directories, a call to this method throws an exception.

Throws:

SecurityError

The application does not have the necessary permissions to delete the directory.

deleteFile():Void

Deletes the file.

Throws:

IOError

The directory does not exist, or the directory could not be deleted. On Windows, you cannot delete a directory that contains a file that is open.

SecurityError

The application does not have the necessary permissions to delete the directory. The following code creates a temporary file and then calls the deleteFile() method to delete it.

import openfl.filesystem.*;
var file:File = File.createTempFile();
trace(file.exists); // true
file.deleteFile();
trace(file.exists); // false

deleteFileAsync():Void

Deletes the file asynchronously.

@events complete Dispatched when the directory has been deleted successfully. @events ioError The directory does not exist or could not be deleted. On Windows, you cannot delete a directory that contains a file that is open.

Throws:

SecurityError

The application does not have the necessary permissions to delete the directory.

getDirectoryListing():Array<File>

Returns an array of File objects corresponding to files and directories in the directory represented by this File object. This method does not explore the contents of subdirectories.

Returns:

Array An array of File objects. The following code shows how to use the getDirectoryListing() method to enumerate the contents of the user directory.

import openfl.filesystem.File;
var directory:File = File.userDirectory;
var list:Array = directory.getDirectoryListing();
for (var i:uint = 0; i < list.length; i++) {
	trace(list[i].nativePath);
}

getDirectoryListingAsync():Void

Asynchronously retrieves an array of File objects corresponding to the contents of the directory represented by this File object.

@events ioError You do not have adequate permissions to read this directory, or the directory does not exist. @events directoryListing The directory contents have been enumerated successfully. The contents event includes a files property, which is the resulting array of File objects.

The following code shows how to use the getDirectoryListingAsync() method to enumerate the contents of the user directory.

import openfl.filesystem.File;
import openfl.events.FileListEvent;

var directory:File = File.userDirectory;
directory.getDirectoryListingAsync();
directory.addEventListener(FileListEvent.DIRECTORY_LISTING, directoryListingHandler);

function directoryListingHandler(event:FileListEvent):void {
	var list:Array = event.files;
	for (var i:uint = 0; i < list.length; i++) {
		trace(list[i].nativePath);
	}
}

@:value({ useDotDot : false })getRelativePath(ref:FileReference, useDotDot:Bool = false):String

Finds the relative path between two File paths.

The relative path is the list of components that can be appended to (resolved against) this reference in order to locate the second (parameter) reference. The relative path is returned using the "/" separator character.

Optionally, relative paths may include ".." references, but such paths will not cross conspicuous volume boundaries.

Parameters:

ref

A File object against which the path is given.

useDotDot

Specifies whether the resulting relative path can use ".." components.

Returns:

String The relative path between this file (or directory) and the ref file (or directory), if possible; otherwise null.

Throws:

ArgumentError

The reference is null.

SecurityError

The caller is not in the application security sandbox.

@:value({ overwrite : false })moveTo(newLocation:FileReference, overwrite:Bool = false):Void

Moves the file or directory at the location specified by this File object to the location specified by the destination parameter.

To rename a file, set the destination parameter to point to a path that is in the file's directory, but with a different filename.

The move process creates any required parent directories (if possible).

Parameters:

newLocation

The target location for the move. This object specifies the path to the resulting (moved) file or directory, not the path to the containing directory.

overwrite

If false, the move fails if the target file already exists. If true, the operation overwrites any existing file or directory of the same name.

Throws:

IOError

The source does not exist; or the destination exists and overwrite is set to false; or the source file or directory could not be moved to the target location; or the source and destination refer to the same file or folder and overwrite is set to true. On Windows, you cannot move a file that is open or a directory that contains a file that is open.

SecurityError

The application does not have the necessary permissions to move the file. The following code shows how to use the moveTo() method to rename a file. The original filename is test1.txt and the resulting filename is test2.txt. Since both the source and destination File object point to the same directory (the Apollo Test subdirectory of the user's documents directory), the moveTo() method renames the file, rather than moving it to a new directory. Before running this code, create a test1.txt file in the OpenFL Test subdirectory of the documents directory on your computer. When you set the overwrite parameter to true, the operation overwrites any existing test2.txt file.

import openfl.filesystem.File;
import openfl.events.Event;
var sourceFile:File = File.documentsDirectory;
sourceFile = sourceFile.resolvePath("OpenFL Test/test1.txt");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("Apollo Test/test2.txt");
try
{
	sourceFile.moveTo(destination, true);
}
catch (error:Error)
{
	trace("Error:" + error.message);
}

@:value({ overwrite : false })moveToAsync(newLocation:FileReference, overwrite:Bool = false):Void

Begins moving the file or directory at the location specified by this File object to the location specified by the newLocation parameter.

To rename a file, set the destination parameter to point to a path that is in the file's directory, but with a different filename.

The move process creates any required parent directories (if possible).

Parameters:

newLocation

The target location for the move. This object specifies the path to the resulting (moved) file or directory, not the path to the containing directory.

overwrite

If false, the move fails if the target file already exists. If true, the operation overwrites any existing file or directory of the same name.

Throws:

SecurityError

The application does not have the necessary permissions to move the file. The following code shows how to use the moveToAsync() method to rename a file. The original filename is test1.txt and the resulting name is test2.txt. Since both the source and destination File object point to the same directory (the Apollo Test subdirectory of the user's documents directory), the moveToAsync() method renames the file, rather than moving it to a new directory. Before running this code, create a test1.txt file in the Apollo Test subdirectory of the documents directory on your computer. When you set overwrite parameter to true, the operation overwrites any existing test2.txt file.

import openfl.filesystem.File;
import openfl.events.Event;
var sourceFile:File = File.documentsDirectory;
sourceFile = sourceFile.resolvePath("Apollo Test/test1.txt");
var destination:File = File.documentsDirectory;
destination = destination.resolvePath("Apollo Test/test2.txt");
sourceFile.moveToAsync(destination, true);
sourceFile.addEventListener(Event.COMPLETE, fileMoveCompleteHandler);
function fileMoveCompleteHandler(event:Event):void
{
	trace("Done.")
}
		```

Events:

complete

Dispatched when the file or directory has been successfully moved.

ioError

The source does not exist; or the destination exists and overwrite is false; or the source could not be moved to the target; or the source and destination refer to the same file or folder and overwrite is set to true. On Windows, you cannot move a file that is open or a directory that contains a file that is open.

openWithDefaultApplication():Void

Opens the file in the application registered by the operating system to open this file type.

resolvePath(path:String):File

Creates a new File object with a path relative to this File object's path, based on the path parameter (a string).

You can use a relative path or absolute path as the path parameter.

If you specify a relative path, the given path is "appended" to the path of the File object. However, use of ".." in the path can return a resulting path that is not a child of the File object. The resulting reference need not refer to an actual file system location.

If you specify an absolute file reference, the method returns the File object pointing to that path. The absolute file reference should use valid native path syntax for the user's operating system (such as "C:\test" on Windows). Do not use a URL (such as "file:///c:/test") as the path parameter.

All resulting paths are normalized as follows:

Any "." element is ignored.
Any ".." element consumes its parent entry.
No ".." reference that reaches the file system root or the application-persistent storage root passes
that node; it is ignored.

You should always use the forward slash (/) character as the path separator. On Windows, you can also use the backslash () character, but you should not. Using the backslash character can lead to applications that do not work on other platforms.

Filenames and directory names are case-sensitive on Linux.

Parameters:

path

The path to append to this File object's path (if the path parameter is a relative path); or the path to return (if the path parameter is an absolute path).

Returns:

File A new File object pointing to the resulting path.

Inherited Variables

Defined by FileReference

read onlycreationDate:Date

The creation date of the file on the local disk. If the object is was not populated, a call to get the value of this property returns null.

Throws:

IOError

If the file information cannot be accessed, an exception is thrown with a message indicating a file I/O error.

IllegalOperationError

If the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the creationDate property is null.

read onlycreator:String

The Macintosh creator type of the file, which is only used in Mac OS versions prior to Mac OS X. In Windows or Linux, this property is null. If the FileReference object was not populated, a call to get the value of this property returns null.

Throws:

IllegalOperationError

On Macintosh, if the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the creator property is null.

read onlydata:ByteArray

The ByteArray object representing the data from the loaded file after a successful call to the load() method.

Throws:

IOError

If the file cannot be opened or read, or if a similar error is encountered in accessing the file, an exception is thrown with a message indicating a file I/O error. In this case, the value of the data property is null.

IllegalOperationError

If the load() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the data property is null.

read onlyextension:String

The filename extension.

A file's extension is the part of the name following (and not including) the final dot ("."). If there is no dot in the filename, the extension is null.

Note: You should use the extension property to determine a file's type; do not use the creator or type properties. You should consider the creator and type properties to be considered deprecated. They apply to older versions of Mac OS.

Throws:

IllegalOperationError

If the reference is not initialized

read onlymodificationDate:Date

The date that the file on the local disk was last modified. If the FileReference object was not populated, a call to get the value of this property returns null.

Throws:

IOError

If the file information cannot be accessed, an exception is thrown with a message indicating a file I/O error.

IllegalOperationError

If the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the modificationDate property is null.

read onlyname:String

The name of the file on the local disk. If the FileReference object was not populated (by a valid call to FileReference.download() or FileReference.browse()), Flash Player throws an error when you try to get the value of this property. All the properties of a FileReference object are populated by calling the browse() method. Unlike other FileReference properties, if you call the download() method, the name property is populated when the select event is dispatched.

Throws:

IllegalOperationError

If the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful.

read onlysize:Float

The size of the file on the local disk in bytes. If size is 0, an exception is thrown.

Note: In the initial version of ActionScript 3.0, the size property was defined as a uint object, which supported files with sizes up to about 4 GB. It was later implemented as a Number object to support larger files. In OpenFL, it is Float to match Number.

Throws:

IOError

If the file cannot be opened or read, or if a similar error is encountered in accessing the file, an exception is thrown with a message indicating a file I/O error.

IllegalOperationError

If the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful.

read onlytype:String

The file type. In Windows or Linux, this property is the file extension. On the Macintosh, this property is the four-character file type, which is only used in Mac OS versions prior to Mac OS X. If the FileReference object was not populated, a call to get the value of this property returns null.

For Windows, Linux, and Mac OS X, the file extension ?the portion of the name property that follows the last occurrence of the dot (.) character ?identifies the file type.

Throws:

IllegalOperationError

If the FileReference.browse(), FileReferenceList.browse(), or FileReference.download() method was not called successfully, an exception is thrown with a message indicating that functions were called in the incorrect sequence or an earlier call was unsuccessful. In this case, the value of the type property is null.

Inherited Methods

Defined by FileReference

@:value({ defaultFileName : null })download(request:URLRequest, ?defaultFileName:String):Void

Opens a dialog box that lets the user download a file from a remote server. Although Flash Player has no restriction on the size of files you can upload or download, the player officially supports uploads or downloads of up to 100 MB. The download() method first opens an operating-system dialog box that asks the user to enter a filename and select a location on the local computer to save the file. When the user selects a location and confirms the download operation (for example, by clicking Save), the download from the remote server begins. Listeners receive events to indicate the progress, success, or failure of the download. To ascertain the status of the dialog box and the download operation after calling download(), your code must listen for events such as cancel, open, progress, and complete.

The FileReference.upload() and FileReference.download() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any upload or download that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload or download is expected to continue.

When the file is downloaded successfully, the properties of the FileReference object are populated with the properties of the local file. The complete event is dispatched if the download is successful.

Only one browse() or download() session can be performed at a time (because only one dialog box can be invoked at a time).

This method supports downloading of any file type, with either HTTP or HTTPS.

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

Note: If your server requires user authentication, only SWF files running in a browser ?that is, using the browser plug-in or ActiveX control ?can provide a dialog box to prompt the user for a user name and password for authentication, and only for downloads. For uploads using the plug-in or ActiveX control, or for uploads and downloads using the stand-alone or external player, the file transfer fails.

When you use this method , consider the Flash Player security model:

  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a resource by adding a URL policy file.
  • You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.
  • In Flash Player 10 and Flash Player 9 Update 5, you can only call this method successfully in response to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling this method results in Flash Player throwing an Error exception.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) is not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: <a href="http://www.adobe.com/go/devnet_security_en" scope="external">Security.

When you download a file using this method, it is flagged as downloaded on operating systems that flag downloaded files:

  • Windows XP service pack 2 and later, and on Windows Vista
  • Mac OS 10.5 and later

Some operating systems, such as Linux, do not flag downloaded files.

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.

In Adobe AIR, the download dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Parameters:

request

The URLRequest object. The url property of the URLRequest object should contain the URL of the file to download to the local computer. If this parameter is null, an exception is thrown. The requestHeaders property of the URLRequest object is ignored; custom HTTP request headers are not supported in uploads or downloads. To send POST or GET parameters to the server, set the value of URLRequest.data to your parameters, and set URLRequest.method to either URLRequestMethod.POST or URLRequestMethod.GET. On some browsers, URL strings are limited in length. Lengths greater than 256 characters may fail on some browsers or servers.

defaultFileName

The default filename displayed in the dialog box for the file to be downloaded. This string must not contain the following characters: / \ : * ? " < > | % If you omit this parameter, the filename of the remote URL is parsed and used as the default.

Throws:

ArgumentError

If url.data is of type ByteArray, an exception is thrown. For use with the FileReference.upload() and FileReference.download() methods, url.data can only be of type URLVariables or String.

Error

If the method is not called in response to a user action, such as a mouse event or keypress event.

IllegalOperationError

Thrown in the following situations: 1) Another browse session is in progress; only one file browsing session can be performed at a time. 2) The value passed to request does not contain a valid path or protocol. 3) The filename to download contains prohibited characters. 4) A setting in the user's mms.cfg file prohibits this operation.

MemoryError

This error can occur for the following reasons: 1) Flash Player cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to the FileReference.download() method is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to the FileReference.download() method is set to perform a POST operation.

SecurityError

Local untrusted content may not communicate with the Internet. To avoid this situation, reclassify this SWF file as local-with-networking or trusted. This exception is thrown with a message indicating the filename and the URL that may not be accessed because of local file security restrictions.

SecurityError

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

Events:

cancel

Dispatched when the user dismisses the dialog box.

complete

Dispatched when the file download operation successfully completes.

ioError

Dispatched for any of the following reasons: An input/output error occurs while the file is being read or transmitted. SWF content running in the stand-alone or external versions of Flash Player tries to download a file from a server that requires authentication. During download, the standalone and external players do not provide a means for users to enter passwords. If a SWF file in these players tries to download a file from a server that requires authentication, the download fails. File download can succeed only in the ActiveX control and browser plug-in players.

open

Dispatched when a download operation starts.

progress

Dispatched periodically during the file download operation.

securityError

Dispatched when a download fails because of a security error.

select

Dispatched when the user selects a file for download from the dialog box.

load():Void

Starts the load of a local file selected by a user. Although Flash Player has no restriction on the size of files you can upload, download, load or save, it officially supports sizes of up to 100 MB. For content running in Flash Player, you must call the FileReference.browse() or FileReferenceList.browse() method before you call the load() method. However, content running in AIR in the application sandbox can call the load() method of a File object without first calling the browse() method. (The AIR File class extends the FileReference class.) Listeners receive events to indicate the progress, success, or failure of the load. Although you can use the FileReferenceList object to let users select multiple files to load, you must load the files one by one. To load the files one by one, iterate through the FileReferenceList.fileList array of FileReference objects.

Adobe AIR also includes the FileStream class which provides more options for reading files.

The FileReference.upload(), FileReference.download(), FileReference.load() and FileReference.save() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any transaction that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload, download, load or save is expected to continue.

If the file finishes loading successfully, its contents are stored as a byte array in the data property of the FileReference object.

The following security considerations apply:

  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a resource by adding a cross-domain policy file.
  • You can prevent a file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

However, these considerations do not apply to AIR content in the application sandbox.

Note that when publishing to Flash Player 10 or AIR 1.5, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, the application throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10 and AIR 1.5. Previous versions of Flash Player or AIR are unaffected by this restriction on simultaneous multiple operations.

In Adobe AIR, the file-browsing dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Throws:

IllegalOperationError

Thrown in the following situations: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) A setting in the user's mms.cfg file prohibits this operation.

MemoryError

This error can occur if the application cannot allocate memory for the file. The file may be too large or available memory may be too low.

Events:

complete

Dispatched when the file load operation completes successfully.

ioError

Invoked if the load fails because of an input/output error while the application is reading or writing the file.

open

Dispatched when an load operation starts.

progress

Dispatched periodically during the file load operation.

@:value({ defaultFileName : null })save(data:Dynamic, ?defaultFileName:String):Void

Opens a dialog box that lets the user save a file to the local filesystem. Although Flash Player has no restriction on the size of files you can upload, download, load or save, the player officially supports sizes of up to 100 MB. The save() method first opens an operating-system dialog box that asks the user to enter a filename and select a location on the local computer to save the file. When the user selects a location and confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box and the save operation after calling save(), your code must listen for events such as cancel, open, progress, and complete.

Adobe AIR also includes the FileStream class which provides more options for saving files locally.

The FileReference.upload(), FileReference.download(), FileReference.load() and FileReference.save() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any transaction that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload, download, load or save is expected to continue.

When the file is saved successfully, the properties of the FileReference object are populated with the properties of the local file. The complete event is dispatched if the save is successful.

Only one browse() or save() session can be performed at a time (because only one dialog box can be invoked at a time).

In Flash Player, you can only call this method successfully in response to a user event (for example, in an event handler for a mouse click or keypress event). Otherwise, calling this method results in Flash Player throwing an Error exception. This limitation does not apply to AIR content in the application sandbox.

In Adobe AIR, the save dialog is not always displayed in front of windows that are "owned" by another window (windows that have a non-null owner property). To avoid window ordering issues, hide owned windows before calling this method.

Parameters:

data

The data to be saved. The data can be in one of several formats, and will be treated appropriately: If the value is null, the application throws an ArgumentError exception. If the value is a String, it is saved as a UTF-8 text file. If the value is XML, it is written to a text file in XML format, with all formatting preserved. If the value is a ByteArray object, it is written to a data file verbatim. * If the value is none of the above, the save() method calls the toString() method of the object to convert the data to a string, and it then saves the data as a text file. If that fails, the application throws an ArgumentError exception.

defaultFileName

The default filename displayed in the dialog box for the file to be saved. This string must not contain the following characters: / \ : * ? " < > | % If a File object calls this method, the filename will be that of the file the File object references. (The AIR File class extends the FileReference class.)

Throws:

ArgumentError

If data is not of type ByteArray, and it does not have a toString() method, an exception is thrown. If data is not of type XML, and it does not have a toXMLString() method, an exception is thrown.

Error

If the method is not called in response to a user action, such as a mouse event or keypress event.

IllegalOperationError

Thrown in the following situations: 1) Another browse session is in progress; only one file browsing session can be performed at a time. 2) The filename to download contains prohibited characters. 3) A setting in the user's mms.cfg file prohibits this operation.

MemoryError

This error can occur if Flash Player cannot allocate memory for the file. The file may be too large or available memory may be too low.

Events:

cancel

Dispatched when the user dismisses the dialog box.

complete

Dispatched when the file download operation successfully completes.

ioError

Dispatched if an input/output error occurs while the file is being read or transmitted.

open

Dispatched when a download operation starts.

progress

Dispatched periodically during the file download operation.

select

Dispatched when the user selects a file for download from the dialog box.

@:value({ testUpload : false, uploadDataFieldName : "Filedata" })upload(request:URLRequest, uploadDataFieldName:String = "Filedata", testUpload:Bool = false):Void

Starts the upload of the file to a remote server. Although Flash Player has no restriction on the size of files you can upload or download, the player officially supports uploads or downloads of up to 100 MB. You must call the FileReference.browse() or FileReferenceList.browse() method before you call this method. For the Adobe AIR File class, which extends the FileReference class, you can use the upload() method to upload any file. For the FileReference class (used in Flash Player), the user must first select a file.

Listeners receive events to indicate the progress, success, or failure of the upload. Although you can use the FileReferenceList object to let users select multiple files for upload, you must upload the files one by one; to do so, iterate through the FileReferenceList.fileList array of FileReference objects.

The FileReference.upload() and FileReference.download() functions are nonblocking. These functions return after they are called, before the file transmission is complete. In addition, if the FileReference object goes out of scope, any upload or download that is not yet completed on that object is canceled upon leaving the scope. Be sure that your FileReference object remains in scope for as long as the upload or download is expected to continue.

The file is uploaded to the URL passed in the url parameter. The URL must be a server script configured to accept uploads. Flash Player uploads files by using the HTTP POST method. The server script that handles the upload should expect a POST request with the following elements:

  • Content-Type of multipart/form-data
  • Content-Disposition with a name attribute set to "Filedata" by default and a filename attribute set to the name of the original file
  • The binary contents of the file

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

For a sample POST request, see the description of the uploadDataFieldName parameter. You can send POST or GET parameters to the server with the upload() method; see the description of the request parameter.

If the testUpload parameter is true, and the file to be uploaded is bigger than approximately 10 KB, Flash Player on Windows first sends a test upload POST operation with zero content before uploading the actual file, to verify that the transmission is likely to succeed. Flash Player then sends a second POST operation that contains the actual file content. For files smaller than 10 KB, Flash Player performs a single upload POST with the actual file content to be uploaded. Flash Player on Macintosh does not perform test upload POST operations.

Note: If your server requires user authentication, only SWF files running in a browser ?that is, using the browser plug-in or ActiveX control ?can provide a dialog box to prompt the user for a username and password for authentication, and only for downloads. For uploads using the plug-in or ActiveX control, or for uploads and downloads using the stand-alone or external player, the file transfer fails.

When you use this method , consider the Flash Player security model:

  • Loading operations are not allowed if the calling SWF file is in an untrusted local sandbox.
  • The default behavior is to deny access between sandboxes. A website can enable access to a resource by adding a URL policy file.
  • You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

However, in Adobe AIR, content in the application security sandbox (content installed with the AIR application) are not restricted by these security limitations.

For more information related to security, see the Flash Player Developer Center Topic: <a href="http://www.adobe.com/go/devnet_security_en" scope="external">Security.

Note that because of new functionality added to the Flash Player, when publishing to Flash Player 10, you can have only one of the following operations active at one time: FileReference.browse(), FileReference.upload(), FileReference.download(), FileReference.load(), FileReference.save(). Otherwise, Flash Player throws a runtime error (code 2174). Use FileReference.cancel() to stop an operation in progress. This restriction applies only to Flash Player 10. Previous versions of Flash Player are unaffected by this restriction on simultaneous multiple operations.

Parameters:

request

The URLRequest object; the url property of the URLRequest object should contain the URL of the server script configured to handle upload through HTTP POST calls. On some browsers, URL strings are limited in length. Lengths greater than 256 characters may fail on some browsers or servers. If this parameter is null, an exception is thrown. The requestHeaders property of the URLRequest object is ignored; custom HTTP request headers are not supported in uploads or downloads. The URL can be HTTP or, for secure uploads, HTTPS. To use HTTPS, use an HTTPS url in the url parameter. If you do not specify a port number in the url parameter, port 80 is used for HTTP and port 443 us used for HTTPS, by default.

To send POST or GET parameters to the server, set the data property of the URLRequest object to your parameters, and set the method property to either URLRequestMethod.POST or URLRequestMethod.GET.

uploadDataFieldName

The field name that precedes the file data in the upload POST operation. The uploadDataFieldName value must be non-null and a non-empty String. By default, the value of uploadDataFieldName is "Filedata", as shown in the following sample POST request: <pre xml:space="preserve"> Content-Type: multipart/form-data; boundary=AaB03x --AaB03x Content-Disposition: form-data; name="Filedata"; filename="example.jpg" Content-Type: application/octet-stream ... contents of example.jpg ... --AaB03x--

testUpload

A setting to request a test file upload. If testUpload is true, for files larger than 10 KB, Flash Player attempts a test file upload POST with a Content-Length of 0. The test upload checks whether the actual file upload will be successful and that server authentication, if required, will succeed. A test upload is only available for Windows players.

Throws:

ArgumentError

Thrown in the following situations: 1) The uploadDataFieldName parameter is an empty string. 2) url.data is of type ByteArray. For use with the FileReference.upload() and FileReference.download() methods, url.data may only be of type URLVariables or String. 3) In the AIR runtime (in the application security sandbox), the method of the URLRequest is not GET or POST (use uploadEncoded() instead).

IllegalOperationError

Thrown in the following situations: 1) Another FileReference or FileReferenceList browse session is in progress; only one file browsing session may be performed at a time. 2) The URL parameter is not a valid path or protocol. File upload must use HTTP, and file download must use FTP or HTTP. 3) The uploadDataFieldName parameter is set to null. 4) A setting in the user's mms.cfg file prohibits this operation.

MemoryError

This error can occur for the following reasons: 1) Flash Player cannot convert the URLRequest.data parameter from UTF8 to MBCS. This error is applicable if the URLRequest object passed to FileReference.upload() is set to perform a GET operation and if System.useCodePage is set to true. 2) Flash Player cannot allocate memory for the POST data. This error is applicable if the URLRequest object passed to FileReference.upload() is set to perform a POST operation.

SecurityError

Local untrusted SWF files may not communicate with the Internet. To avoid this situation, reclassify this SWF file as local-with-networking or trusted. This exception is thrown with a message indicating the name of the local file and the URL that may not be accessed.

SecurityError

You cannot connect to commonly reserved ports. For a complete list of blocked ports, see "Restricting Networking APIs" in the ActionScript 3.0 Developer's Guide.

Events:

complete

Dispatched when the file upload operation completes successfully.

httpResponseStatus

The upload operation completes successfully and the server returns a response URL and response headers.

httpStatus

Dispatched when an upload fails because of an HTTP error.

ioError

Invoked in any of the following situations: The upload fails because of an input/output error while Flash Player or Adobe AIR is reading, writing, or transmitting the file. The upload fails because an attempt to upload a file to a server that requires authentication (such as a user name and password). During upload, no mean is provided for users to enter passwords. * The upload fails because the url parameter contains an invalid protocol. FileReference.upload() must use HTTP or HTTPS.

open

Dispatched when an upload operation starts.

progress

Dispatched periodically during the file upload operation.

securityError

Dispatched when an upload fails because of a security violation.

uploadCompleteData

Dispatched when data has been received from the server after a successful file upload.

Defined by EventDispatcher

@:value({ useWeakReference : false, priority : 0, useCapture : false })addEventListener<T>(type:EventType<T>, listener:T ‑> Void, useCapture:Bool = false, priority:Int = 0, useWeakReference:Bool = false):Void

Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. You can register event listeners on all nodes in the display list for a specific type of event, phase, and priority.

After you successfully register an event listener, you cannot change its priority through additional calls to addEventListener(). To change a listener's priority, you must first call removeListener(). Then you can register the listener again with the new priority level.

Keep in mind that after the listener is registered, subsequent calls to addEventListener() with a different type or useCapture value result in the creation of a separate listener registration. For example, if you first register a listener with useCapture set to true, it listens only during the capture phase. If you call addEventListener() again using the same listener object, but with useCapture set to false, you have two separate listeners: one that listens during the capture phase and another that listens during the target and bubbling phases.

You cannot register an event listener for only the target phase or the bubbling phase. Those phases are coupled during registration because bubbling applies only to the ancestors of the target node.

If you no longer need an event listener, remove it by calling removeEventListener(), or memory problems could result. Event listeners are not automatically removed from memory because the garbage collector does not remove the listener as long as the dispatching object exists(unless the useWeakReference parameter is set to true).

Copying an EventDispatcher instance does not copy the event listeners attached to it.(If your newly created node needs an event listener, you must attach the listener after creating the node.) However, if you move an EventDispatcher instance, the event listeners attached to it move along with it.

If the event listener is being registered on a node while an event is being processed on this node, the event listener is not triggered during the current phase but can be triggered during a later phase in the event flow, such as the bubbling phase.

If an event listener is removed from a node while an event is being processed on the node, it is still triggered by the current actions. After it is removed, the event listener is never invoked again(unless registered again for future processing).

Parameters:

type

The type of event.

useCapture

Determines whether the listener works in the capture phase or the target and bubbling phases. If useCapture is set to true, the listener processes the event only during the capture phase and not in the target or bubbling phase. If useCapture is false, the listener processes the event only during the target or bubbling phase. To listen for the event in all three phases, call addEventListener twice, once with useCapture set to true, then again with useCapture set to false.

priority

The priority level of the event listener. The priority is designated by a signed 32-bit integer. The higher the number, the higher the priority. All listeners with priority n are processed before listeners of priority n-1. If two or more listeners share the same priority, they are processed in the order in which they were added. The default priority is 0.

useWeakReference

Determines whether the reference to the listener is strong or weak. A strong reference(the default) prevents your listener from being garbage-collected. A weak reference does not.

Class-level member functions are not subject to garbage collection, so you can set useWeakReference to true for class-level member functions without subjecting them to garbage collection. If you set useWeakReference to true for a listener that is a nested inner function, the function will be garbage-collected and no longer persistent. If you create references to the inner function(save it in another variable) then it is not garbage-collected and stays persistent.

Weak references are supported on some OpenFL targets only, including html5, cpp, and flash/air. On other targets, this parameter is ignored, and the reference will be strong instead.

Throws:

ArgumentError

The listener specified is not a function.

dispatchEvent(event:Event):Bool

Dispatches an event into the event flow. The event target is the EventDispatcher object upon which the dispatchEvent() method is called.

Parameters:

event

The Event object that is dispatched into the event flow. If the event is being redispatched, a clone of the event is created automatically. After an event is dispatched, its target property cannot be changed, so you must create a new copy of the event for redispatching to work.

Returns:

A value of true if the event was successfully dispatched. A value of false indicates failure or that preventDefault() was called on the event.

Throws:

Error

The event dispatch recursion limit has been reached.

hasEventListener(type:String):Bool

Checks whether the EventDispatcher object has any listeners registered for a specific type of event. This allows you to determine where an EventDispatcher object has altered handling of an event type in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, use willTrigger().

The difference between hasEventListener() and willTrigger() is that hasEventListener() examines only the object to which it belongs, whereas willTrigger() examines the entire event flow for the event specified by the type parameter.

When hasEventListener() is called from a LoaderInfo object, only the listeners that the caller can access are considered.

Parameters:

type

The type of event.

Returns:

A value of true if a listener of the specified type is registered; false otherwise.

@:value({ useCapture : false })removeEventListener<T>(type:EventType<T>, listener:T ‑> Void, useCapture:Bool = false):Void

Removes a listener from the EventDispatcher object. If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect.

Parameters:

type

The type of event.

useCapture

Specifies whether the listener was registered for the capture phase or the target and bubbling phases. If the listener was registered for both the capture phase and the target and bubbling phases, two calls to removeEventListener() are required to remove both, one call with useCapture() set to true, and another call with useCapture() set to false.

toString():String

willTrigger(type:String):Bool

Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type. This method returns true if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.

The difference between the hasEventListener() and the willTrigger() methods is that hasEventListener() examines only the object to which it belongs, whereas the willTrigger() method examines the entire event flow for the event specified by the type parameter.

When willTrigger() is called from a LoaderInfo object, only the listeners that the caller can access are considered.

Parameters:

type

The type of event.

Returns:

A value of true if a listener of the specified type will be triggered; false otherwise.