File API
The File API allows you to read and write files based on the native file system of the device.
The File API methods allows you to perform various tasks like storing files in a temporary or persistent storage location for your app or storing files in other platform dependent locations. It also provides you information about the file and access their content in your app or web page. The File API is supported on Windows Desktop Browsers, Android Mobile Browsers and iOS Mobile Browsers, and Web platforms. Specific methods which are part of the File API may be available only in a single platform.
The following are some of the main functions of File API:
- Access the file system
- Return the file path of the specified file.
- Create file and directories
- Write to files
- Read files
- Extract file from a storage location
- Delete a file or directory
File Storage Locations
Methods
Objects
File System Directories
This section explains the URLs to important file-system directories are provided. Each URL is in the form file:///path/to/spot/, and can be converted to a DirectoryEntry using window.resolveLocalFileSystemURL().
- $m.file.applicationDirectory: Read-only directory where the application is installed.
- $m.file.applicationStorageDirectory: Root directory of the application sandbox. All data contained within is private to the application.
- $m.file.dataDirectory: Persistent and private data storage within the application sandbox using internal memory. On Android, if you need to use external memory, use .externalDataDirectory. On iOS, this directory is not synced with iCloud. Use .syncedDataDirectory to sync the directory with iCloud.
- $m.file.cacheDirectory: Directory for cached data files or any files that your app can re-create easily.
- $m.file.externalApplicationStorageDirectory: Application space on external storage for Android.
- $m.file.externalDataDirectory: App-specific data files on external storage for Android.
- $m.file.externalCacheDirectory: Application cache on external storage for Android.
- $m.file.externalRootDirectory: External storage root for Android.
- $m.file.tempDirectory: Temp directory that the OS can clear when required for iOS and Windows.
- $m.file.syncedDataDirectory: Holds app-specific files that should be synced for iOS and Windows.
- $m.file.documentsDirectory: Files private to the app, but that are meaningful to other application. For example, Office files.
- $m.file.sharedDirectory: Files globally available to all applications.
Android File System Layout
Device Path | $m.file.*
|
AndroidExtraFileSystems
|
r/w? | persistent? | OS clears | private |
---|---|---|---|---|---|---|
file:///android_asset/
|
applicationDirectory | assets | r | N/A | N/A | Yes |
/data/data/<app-id>/
|
applicationStorageDirectory | - | r/w | N/A | N/A | Yes |
cache
|
cacheDirectory | cache | r/w | Yes | Yes* | Yes |
files
|
dataDirectory | files | r/w | Yes | No | Yes |
Documents
|
- | documents | r/w | Yes | No | Yes |
<sdcard>/
|
externalRootDirectory | sdcard | r/w | Yes | No | No |
Android/data/<app-id>/
|
externalApplicationStorageDirectory | - | r/w | Yes | No | No |
cache
|
externalCacheDirectory | cache-external | r/w | Yes | No** | No |
files
|
externalDataDirectory | files-external | r/w | Yes | No | No |
iOS File System Layout
Device Path | $m.file.*
|
iosExtraFileSystems
|
r/w? | persistent? | OS clears | sync | private |
---|---|---|---|---|---|---|---|
/var/mobile/Applications/<UUID>/
|
applicationStorageDirectory | - | r | N/A | N/A | N/A | Yes |
appname.app/
|
applicationDirectory | bundle | r | N/A | N/A | N/A | Yes |
www/
|
- | - | r | N/A | N/A | N/A | Yes |
Documents/
|
documentsDirectory | documents | r/w | Yes | No | Yes | Yes |
NoCloud/
|
- | documents-nosync | r/w | Yes | No | No | Yes |
Library
|
- | library | r/w | Yes | No | Yes | Yes |
NoCloud/
|
dataDirectory | library-nosync | r/w | Yes | No | No | Yes |
Cloud/
|
syncedDataDirectory | - | r/w | Yes | No | Yes | Yes |
Caches/
|
cacheDirectory | cache | r/w | Yes | Yes | No | Yes |
tmp/
|
tempDirectory | - | r/w | No | Yes | No | Yes |
chooseFile
Use this method to display a file picker dialog and retrieve an object that represents the selected file with the file path.
Syntax
$m.chooseFile(success_callback, error_callback);
Parameters
success_callback
: (function
). Callback function that provides the object or the file path.
error_callback
: (function
). Callback function that provides the error object. The error object contains,
- message: (
String
). A short description of the error. - description: (
String
). A detailed description of the error.
Return
The object that represents the selected file or the path of the file.
Example
$m,chooseFile(success_callback , error_callback)
var success_callback = function(res){
// do something
}
Var error_callback = function(res){
// do something
}
unzipFile
Use this method to extract all the file from a specified zip file to a directory on the file system.
Syntax
$m.unzipFile( srcFile, destination, success_callback, error_callback );
Parameters
success_callback
: (function
). Callback function that provides the success object.
- message: (
String
). A short description of the success.
error_callback
: (function
). Callback function that provides the error object.
- message: (
String
). A short description of the error.
srcFile
: (object
). The full path and file name of the zip archive that needs to be extracted.
destDirectory
: (object
). The path to the directory or the folder where the files would be extracted.
Return
The object that represents the success or error message.
Example
$m.unzipFile( srcFile, destination, success_callback, error_callback );
var success_callback = function(res){
// do something
}
var error_callback = function(res){
// do something
}
var srcFile = new DirectoryEntry("test","/test/","file://asserts_files","file://asserts_files/test")
var destination= new DirectoryEntry("test","/test/","file://asserts_files","file://asserts_files/test")
Objects
DirectoryEntry
An object that represents a directory on a file system.
Syntax
DirectoryEntry( name, path, filesystem, nativeurl );
Properties
name
: (string
). The name of the DirectoryEntry, excluding the path leading to it.
path
: (string
). The full absolute path from the root to the DirectoryEntry.
filesystem
: (string
). The filesystem on which the DirectoryEntry resides.
nativeurl
: (string
). URL for the DirectoryEntry.
Methods:
- getMetadata
- setMetadata
- moveTo
- copyTo
- toURL
- remove
- getParent
- createReader
- getDirectory
- getFile
- removeRecursively
getMetadata
Look up metadata about a directory.
Parameters
successCallback
: (function
). Callback function that is called with a Metadata object.errorCallback
: (function
). Callback function that is called if an error occurs when retrieving the Metadata object.
setMetadata
Set metadata on a directory.
Parameters
successCallback
: (function
). Callback function that is executed when the metadata is successfully set.errorCallback
: (function
). Callback function that is executed when the metadata fails to be set.metadataObject
: (object
) An object that contains the metadata's keys and values.
moveTo
Move a directory to a different location on the file system.
Parameters
Parent
: (DirectoryEntry
). The parent directory you want to move the directory.newname
: (String
). The new name of the directory.successCallback
: (function
). Callback function that is called with the DirectoryEntry object of the new directory.errorCallback
: (function
). Callback function that is called if an error occurs when attempting to move the directory.
copyTo
Copy a directory to a different location on the file system.
Parameters
Parent
: (DirectoryEntry
). The parent directory you want to copy the directory.newname
: (String
). The new name of the directory.successCallback
: (function
). Callback function that is called with the DirectoryEntry object of the new directory.errorCallback
: (function
). Callback function that is called if an error occurs when attempting to copy the underlying directory.
toURL
Returns a URL which is used to locate a directory.
Parameters
NA
remove
Delete a directory. The directory must be empty.
Parameters
successCallback
: (function
). Callback function that is called after the directory has been deleted.errorCallback
: (function
). Callback function that is called if an error occurs when attempting to delete the directory.
getParent
Look up the parent directory.
Parameters
successCallback
: (function
). Callback function that is called with the directory's parent DirectoryEntry.errorCallback
: (function
). A callback that is called if an error occurs when attempting to retrieve the parent DirectoryEntry. Invoked with a FileError object. (Function)
createReader
Create a new DirectoryReader to read entries in a directory.
Parameters
NA
getDirectory
Creates or looks up a directory.
Parameters
Path
: (String
). The path to the directory to be looked up or created.Options
: (Flags
). Options to specify whether the directory is created if it doesn't exist.successCallback
: (function
). Callback functions that is invoked with a DirectoryEntry object.errorCallback
: (function
). Callback that is called if an error occurs creating or looking up the directory.
getFile
Creates or looks up a file.
Parameters
Path
: (String
). The path to the file to be looked up or created.Options
: (Flags
). Options to specify whether the file is created if it doesn't exist.successCallback
: (function
). Callback functions that is invoked with a FileEntry object.errorCallback
: (function
). Callback that is called if an error occurs creating or looking up the file.
removeRecursively
Delete a directory and all of its contents.
Parameters
successCallback
: (function
). Callback function that is called after the DirectoryEntry has been deleted.errorCallback
: (function
). Callback function that is called if an error occurs when attempting to delete the DirectoryEntry.
Example
var de = new DirectoryEntry("test","/test/","file://asserts_files","file://asserts_files/test")
DirectoryReader
An object that lists the files and directories within a directory.
Syntax
var directoryReader = de.createReader();
Methods:
readEntries
Use this method to read the entries in this directory.
Parameters
successCallback
: (function
). Callback function that is passed as an array of FileEntry and DirectoryEntry objects.errorCallback
: (function
). Callback function that is called if an error occurs retrieving the directory listing.
Example
var success_callback = function(res){
// do something
}
Var error_callback = function(res){
// do something
}
// Get a list of all the entries in the directory
directoryReader.readEntries(success_callback ,error_callback);
FileEntry
An object that represents a file on a file system.
Syntax
FileEntry( name, path, filesystem, nativeurl );
Properties
name
: (string
). The name of the FileEntry, excluding the path leading to it.
path
: (string
). The full absolute path from the root to the FileEntry.
filesystem
: (string
). The filesystem on which the FileEntry resides.
nativeurl
: (string
). URL for the FileEntry.
Methods
getMetadata
Look up metadata about a file.
Parameters
successCallback
: (function
). Callback function that is called with the Metadata object.errorCallback
: (function
). A callback that is called if an error happens retrieving the Metadata.
setMetadata
Set metadata on a file.
Parameters
successCallback
: (function
). Callback function that is called when the metadata was successfully set.errorCallback
: (function
). Callback function that is called when the metadata was not successfully set.metadataObject
: (object
). An object that contains the metadata keys and values.
moveTo
Move a file to a different location on the file system.
Parameters
parent
: (DirectoryEntry
). The directory to which to move the file.newname
: (String
). The new name of the file. Defaults to the Entry's current name if unspecified.successCallback
: (function
). Callback function that is called with the FileEntry for the new location.errorCallback
: (function
). Callback function that is called if an error occurs when attempting to move the file.
copyTo
Copy a file to a different location on the file system.
Parameters
parent
: (DirectoryEntry
). The directory to which to move the file.newname
: (String
). The new name of the file. Defaults to the Entry's current name if unspecified.successCallback
: (function
). Callback function that is called with the FileEntry for the new location.errorCallback
: (function
). Callback function that is called if an error happens when attempting to copy the file.
toURL
Return a URL that can be used to locate a file.
Parameters
NA
remove
Delete a file.
Parameters
successCallback
: (function
). Callback function that is called if file deletion is success.errorCallback
: (function
). Callback function that is called if an error occurs when attempting to delete the file.
getParent
Look up the DirectoryEntry containing the file.
Parameters
successCallback
: (function
). Callback function that is called with the file's parent DirectoryEntry. (Function)errorCallback
: (function
). A callback that is called if an error occurs when attempting to retrieve the parent DirectoryEntry.
createWriter
Creates a new FileWriter object associated with the file that the FileEntry represents.
Parameters
successCallback
: (function
). Callback function that is called with the new FileEntry.errorCallback
: (function
). Callback function that is called if an error happens while attempting to create the FileWriter.
file
Creates a file object containing file properties.
Parameters
successCallback
: (function
). Callback function that is called with the file.errorCallback
: (function
). Callback function that is called if an error occurs when creating the file.
Example
var fe = new FileEntry("test","/test/","file://asserts_files/test.txt","file://asserts_files/test.txt")
FileReader
An object which can be used to read data from the file or access it.
Syntax
entry.file(success_callback, error_callback);
Parameters
successCallback
: (function
). Callback function that is called when the accessing the file is a success.errorCallback
: (function
). Callback function that is called when an error occurs while trying to access the file.
Example
function win(file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
// do something
};
reader.readAsDataURL(file);
};
var fail = function (evt) {
console.log(error.code);
};
entry.file(win, fail);
FileSystem
An object that represents a file system.
Syntax
filesystem.root.name
filesystem.name
Properties
name
: (String
). The name of the file system.root
: (DirectoryEntry
). The root directory of the file system.
Example
function onSuccess(fileSystem) {
console.log(fileSystem.name);
console.log(fileSystem.root.name);
}
// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);
FileWriter
An object that allows you to create and write files to the device file system. This object is created for a single file.
Syntax
entry.createWriter(success_callback, error_callback);
Parameters
successCallback
: (function
). Callback function that is called when the FileWriter has been created successfully; the FileWriter is passed into Callback as the only parameter.errorCallback
: (function
). Callback function that is called when an error occurs while trying to create the FileWriter. This callback returns a FileError object describing the error.
Example
function win(writer) {
// fast forwards file pointer to end of file
writer.seek(writer.length);
};
var fail = function(evt) {
console.log(error.code);
};
entry.createWriter(win, fail);
LocalFileSystem
An object that helps you to gain access to a root file system.
Syntax
window.requestFileSystem(storage_type, size, success_callback, error_callback);
Parameters
type
: (Constants
). The storage type of the file system you want to gain access.size
: (value
). The amount of storage space you wish to have allocated for your app's use.successCallback
: (function
). Callback function that is invoked when the file system has been successfully obtained.errorCallback
:(function
). Callback function that is called is an error occurs while attempting to obtain the file system, or if the user denies permission to create or access the file system. The callback returns a FileError object describing the error.
Example
function onSuccess(fileSystem) {
console.log(fileSystem.name);
}
// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);
FileError
The FileError object represents the error conditions that you might encounter while accessing the file system using any of the File API methods.
The objects are passed to File API’s error callbacks. The objects have a code that the developers must read to determine the type of error that occurred.
Parameters
code
: (Value
). The predefined error codes for a specific condition error condition.The following table provides the numeric value associated with each error constants.
Constants Code Description NOT_FOUND_ERR
1 The required file or directory (object) couldn’t be found at the time the operation was processed.
SECURITY_ERR
2 The access to the file or the operation isn’t allowed due to specific restrictions.
ABORT_ERR
3 The operation was aborted.
NOT_READABLE_ERR
4 The file or directory is not readable, perhaps due to permission problems or another concurrently locked by another application. ENCODING_ERR
5 The URL is malformed. Make sure that the URL is complete and valid.
NO_MODIFICATION_ALLOWED_ERR
6 The object (file or directory) can’t be modified due to the state of the underlying file system.
INVALID_STATE_ERR
7 The operation can’t be performed as the current state of the object is invalid.
SYNTAX_ERR
8 An invalid string value is specified.
INVALID_MODIFICATION_ERR
9 The object can’t be modified due to the current state of the object. QUOTA_EXCEEDED_ERR
10 Either there's not enough remaining storage space or the storage quota has reached. TYPE_MISMATCH_ERR
11 The app looked up an object, but type of the object does not match the expected type. PATH_EXISTS_ERR
12 The file or directory with the same path already exists.