File Plugin
Tested Version: 7.0.0
This document is based on the original Cordova docs available at Cordova Docs.
This plugin implements a File API allowing read/write access to files residing on the device. This plugin is based on several specs, including :
The Directories and System extensions Latest
Although most of the plugin code was written when an earlier spec was current.
It also implements the FileWriter spec
While the W3C FileSystem spec is deprecated for web browsers, the FileSystem APIs are supported in Cordova applications with this plugin for the platforms listed in the Supported Platforms list, with the exception of the Browser platform.
To get a few ideas how to use the plugin, check out the sample at the bottom of this page. For additional examples (browser focused), see the HTML5 Rocks' FileSystem article. For an overview of other storage options, refer to Cordova's storage guide.
This plugin defines global cordova.file
object. Although in the global scope, it is not available until after the deviceready
event.
Plugin ID
Adding the Plugin in Monaca
In order to use this plugin, please In order to use this plugin, please enable File
plugin in Monaca Cloud IDE.
Supported Platforms
Android
iOS
Where to Store Files
As of v1.2.0, 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()
.
cordova.file.applicationDirectory
- Read-only directory where the application is installed. (iOS, Android, BlackBerry 10, OSX, windows)cordova.file.applicationStorageDirectory
- Root directory of the application's sandbox; on iOS & windows this location is read-only (but specific subdirectories [like/Documents
on iOS or/localState
on windows] are read-write). All data contained within is private to the app. (iOS, Android, BlackBerry 10, OSX)cordova.file.dataDirectory
- Persistent and private data storage within the application's 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
). (iOS, Android, BlackBerry 10, windows)cordova.file.cacheDirectory
- Directory for cached data files or any files that your app can re-create easily. The OS may delete these files when the device runs low on storage, nevertheless, apps should not rely on the OS to delete files in here. (iOS, Android, BlackBerry 10, OSX, windows)cordova.file.externalApplicationStorageDirectory
- Application space on external storage. (Android)cordova.file.externalDataDirectory
- Where to put app-specific data files on external storage. (Android)cordova.file.externalCacheDirectory
- Application cache on external storage. (Android)cordova.file.externalRootDirectory
- External storage (SD card) root. (Android, BlackBerry 10)cordova.file.tempDirectory
- Temp directory that the OS can clear at will. Do not rely on the OS to clear this directory; your app should always remove files as applicable. (iOS, OSX, windows)cordova.file.syncedDataDirectory
- Holds app-specific files that should be synced (e.g. to iCloud). (iOS, windows)cordova.file.documentsDirectory
- Files private to the app, but that are meaningful to other application (e.g. Office files). Note that for OSX this is the user's~/Documents
directory. (iOS, OSX)cordova.file.sharedDirectory
- Files globally available to all applications (BlackBerry 10)
File System Layouts
Although technically an implementation detail, it can be very useful to know how the cordova.file.*
properties map to physical paths on a real device.
iOS File System Layout
Device Path | cordova.file.* | iosExtraFileSystems | r/w | persistent | OS clears | sync | private |
| applicationStorageDirectory | r | N/A | N/A | N/A | Yes | |
| applicationDirectory | bundle | r | N/A | N/A | N/A | Yes |
| r | N/A | N/A | N/A | Yes | ||
| documentsDirectory | documents | r/w | Yes | No | Yes | Yes |
| documents-nosync | r/w | Yes | No | No | Yes | |
| syncedDataDirectory | r/w | Yes | No | Yes | Yes | |
| cacheDirectory | cache | r/w | Yes* | No*** | No | Yes |
| tempDirectory | r/w | No** | Yes*** | No | Yes |
* Files persist across app restarts and upgrades, but this directory can be cleared whenever the OS desires. Your app should be able to recreate any content that might be deleted.
** Files may persist across app restarts, but do not rely on this behavior. Files are not guaranteed to persist across updates. Your app should remove files from this directory when it is applicable, as the OS does not guarantee when (or even if) these files are removed.
*** The OS may clear the contents of this directory whenever it feels it is necessary, but do not rely on this. You should clear this directory as appropriate for your application.
Android File System Layout
Device Path | cordova.file.* | AndroidExtraFileSystems | r/w | persistent | OS clears | private |
| applicationDirectory | assets | r | N/A | N/A | Yes |
| applicationStorageDirectory | r/w | N/A | N/A | Yes | |
| cacheDirectory | cache | r/w | Yes | Yes* | Yes |
| dataDirectory | files | r/w | Yes | No | Yes |
| documents | r/w | Yes | No | Yes | |
| externalRootDirector | sdcard | r/w*** | Yes | No | No |
| externalApplicationStorageDirectory | r/w | Yes | No | No | |
| externalCacheDirectory | cache-external | r/w | Yes | No** | No |
| externalDataDirectory | files-external | r/w | Yes | No | No |
* The OS may periodically clear this directory, but do not rely on this behavior. Clear the contents of this directory as appropriate for your application. Should a user purge the cache manually, the contents of this directory are removed.
** The OS does not clear this directory automatically; you are responsible for managing the contents yourself. Should the user purge the cache manually, the contents of the directory are removed.
*** As of API 30, these directories are no longer writable.
If external storage can't be mounted, the cordova.file.external*
properties are null
.
Quirks
Android Quirks
Android Persistent storage location
There are multiple valid locations to store persistent files on an Android device. See this page for an extensive discussion of the various possibilities.
Previous versions of the plugin would choose the location of the temporary and persistent files on startup, based on whether the device claimed that the SD Card (or equivalent storage partition) was mounted. If the SD Card was mounted, or if a large internal storage partition was available (such as on Nexus devices,) then the persistent files would be stored in the root of that space. This meant that all Cordova apps could see all of the files available on the card.
If the SD card was not available, then previous versions would store data under /data/data/<packageId>
, which isolates apps from each other, but may still cause data to be shared between users.
It is now possible to choose whether to store files in the internal file storage location, or using the previous logic, with a preference in your application's config.xml
file. To do this, add one of these two lines to config.xml
:
Without this line, the File plugin will use Internal
as the default. If a preference tag is present, and is not one of these values, the application will not start.
If your application has previously been shipped to users, using an older (pre- 3.0.0) version of this plugin, and has stored files in the persistent filesystem, then you should set the preference to Compatibility
if your config.xml does not specify a location for the persistent filesystem. Switching the location to "Internal" would mean that existing users who upgrade their application may be unable to access their previously-stored files, depending on their device.
If your application is new, or has never previously stored files in the persistent filesystem, then the Internal
setting is generally recommended.
Slow recursive operations for /android_asset
Listing asset directories is really slow on Android. You can speed it up though, by adding src/android/build-extras.gradle
to the root of your android project (also requires cordova-android@4.0.0 or greater).
Permission to write to external storage when it's not mounted on Marshmallow
Marshmallow requires the apps to ask for permissions when reading/writing to external locations. By default, your app has permission to write to cordova.file.applicationStorageDirectory
and cordova.file.externalApplicationStorageDirectory
, and the plugin doesn't request permission for these two directories unless external storage is not mounted. However due to a limitation, when external storage is not mounted, it would ask for permission to write to cordova.file.externalApplicationStorageDirectory
.
iOS Quirks
cordova.file.applicationStorageDirectory
is read-only; attempting to store files within the root directory will fail. Use one of the othercordova.file.*
properties defined for iOS (onlyapplicationDirectory
andapplicationStorageDirectory
are read-only).FileReader.readAsText(blob, encoding)
The
encoding
parameter is not supported, and UTF-8 encoding is always in effect.
iOS Persistent storage location
There are two valid locations to store persistent files on an iOS device: the Documents directory and the Library directory. Previous versions of the plugin only ever stored persistent files in the Documents directory. This had the side-effect of making all of an application's files visible in iTunes, which was often unintended, especially for applications which handle lots of small files, rather than producing complete documents for export, which is the intended purpose of the directory.
It is now possible to choose whether to store files in the documents or library directory, with a preference in your application's config.xml
file. To do this, add one of these two lines to config.xml
:
Without this line, the File plugin will use Compatibility
as the default. If a preference tag is present, and is not one of these values, the application will not start.
If your application has previously been shipped to users, using an older (pre- 1.0) version of this plugin, and has stored files in the persistent filesystem, then you should set the preference to Compatibility
. Switching the location to Library
would mean that existing users who upgrade their application would be unable to access their previously-stored files.
If your application is new, or has never previously stored files in the persistent filesystem, then the Library
setting is generally recommended.
Upgrading Notes
In v1.0.0 of this plugin, the FileEntry
and DirectoryEntry
structures have changed, to be more in line with the published specification.
Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location in the fullPath
property of Entry
objects. These paths would typically look like
These paths were also returned by the toURL()
method of the Entry
objects.
With v1.0.0, the fullPath
attribute is the path to the file, relative to the root of the HTML filesystem. So, the above paths would now both be represented by a FileEntry
object with a fullPath
of
If your application works with device-absolute-paths, and you previously retrieved those paths through the fullPath
property of Entry
objects, then you should update your code to use entry.toURL()
instead.
For backwards compatibility, the resolveLocalFileSystemURL()
method will accept a device-absolute-path, and will return an Entry
object corresponding to it, as long as that file exists within either the TEMPORARY
or PERSISTENT
filesystems.
This has particularly been an issue with the File-Transfer plugin, which previously used device-absolute-paths (and can still accept them). It has been updated to work correctly with FileSystem URLs, so replacing entry.fullPath
with entry.toURL()
should resolve any issues getting that plugin to work with files on the device.
In v1.1.0 the return value of toURL()
was changed (see CB-6394) to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use toInternalURL()
now. This method will now return filesystem URLs of the form
which can be used to identify the file uniquely.
In v7.0.0 the return value of toURL()
for Android was updated to return the absolute file://
URL when app content is served from the file://
scheme.
If app content is served from the http(s)://
scheme, a cdvfile
formatted URL will be returned instead. The cdvfile
formatted URL is created from the internal method toInternalURL()
.
An example toInternalURL()
return filesystem URL:
It is recommended to always use the toURL()
to ensure that the correct URL is returned.
cdvfile protocol
Not Supported on Android
Purpose
cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file
can be used for platform-independent file paths. cdvfile paths are supported by core plugins - for example you can download an mp3 file to cdvfile-path via cordova-plugin-file-transfer
and play it via cordova-plugin-media
.
See Where to Store Files, File System Layouts and Configuring the Plugin for more details about available fs roots.
To use cdvfile
as a tag' src
you can convert it to native path via toURL()
method of the resolved fileEntry, which you can get via resolveLocalFileSystemURL
- see examples below. You can also use cdvfile://
paths directly in the DOM, for example:
This method requires following Content Security rules updates:
Add
cdvfile:
scheme toContent-Security-Policy
meta tag of the index page, e.g.:
Add
<access origin="cdvfile://*" />
toconfig.xml
.
Converting cdvfile:// to native path
Converting native path to cdvfile://
Using cdvfile in core plugins
List of Error Codes and Meanings
When an error is thrown, one of the following codes will be used.
Code | Constant |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Configuring the Plugin (Optional)
The set of available filesystems can be configured per-platform. Both iOS and Android recognize a tag in config.xml
which names the filesystems to be installed. By default, all file-system roots are enabled.
Android
files
: The application's internal file storage directoryfiles-external
: The application's external file storage directorysdcard
: The global external file storage directory (this is theroot of the SD card, if one is installed). You must have the
android.permission.WRITE_EXTERNAL_STORAGE
permission to use this.cache
: The application's internal cache directorycache-external
: The application's external cache directoryassets
: The application's bundle (read-only)root
: The entire device filesystem
Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
iOS
library
: The application's Library directorydocuments
: The application's Documents directorycache
: The application's Cache directorybundle
: The application's bundle; the location of the app itselfon disk (read-only)
root
: The entire device filesystem
By default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems, library-nosync
and documents-nosync
, which represent a special non-synced directory within the /Library
or /Documents
filesystem.
Sample: Create Files and Directories, Write, Read, and Append files
The File plugin allows you to do things like store files in a temporary or persistent storage location for your app (sandboxed storage) and to store files in other platform-dependent locations. The code snippets in this section demonstrate different tasks including:
Using cross-platform Cordova file URLs to store your files (see Where to Store Files for more info)
Creating files and directories
Create a persistent file
Before you use the File plugin APIs, you can get access to the file system using requestFileSystem
. When you do this, you can request either persistent or temporary storage. Persistent storage will not be removed unless permission is granted by the user.
When you get file system access using requestFileSystem
, access is granted for the sandboxed file system only (the sandbox limits access to the app itself), not for general access to any file system location on the device. (To access file system locations outside the sandboxed storage, use other methods such as window.resolveLocalFileSystemURL
, which support platform-specific locations. For one example of this, see Append a File.)
Here is a request for persistent storage.
The success callback receives FileSystem object (fs). Use fs.root
to return a DirectoryEntry object, which you can use to create or get a file (by calling getFile
). In this example, fs.root
is a DirectoryEntry object that represents the persistent storage in the sandboxed file system.
The success callback for getFile
receives a FileEntry object. You can use this to perform file write and file read operations.
Create a temporary file
Here is an example of a request for temporary storage. Temporary storage may be deleted by the operating system if the device runs low on memory.
When you are using temporary storage, you can create or get the file by calling getFile
. As in the persistent storage example, this will give you a FileEntry object that you can use for read or write operations.
Write to a file
Once you have a FileEntry object, you can write to the file by calling createWriter
, which returns a FileWriter object in the success callback. Call the write
method of FileWriter to write to the file.
Read a file
You also need a FileEntry object to read an existing file. Use the file property of FileEntry to get the file reference, and then create a new FileReader object. You can use methods like readAsText
to start the read operation. When the read operation is complete, this.result
stores the result of the read operation.
Append a file using alternative methods
Of course, you will often want to append existing files instead of creating new ones. Here is an example of that. This example shows another way that you can access the file system using window.resolveLocalFileSystemURL. In this example, pass the cross-platform Cordova file URL, cordova.file.dataDirectory, to the function. The success callback receives a DirectoryEntry object, which you can use to do things like create a file.
In addition to this usage, you can use resolveLocalFileSystemURL
to get access to some file system locations that are not part of the sandboxed storage system. See Where to store Files for more information; many of these storage locations are platform-specific. You can also pass cross-platform file system locations to resolveLocalFileSystemURL
using the cdvfile protocol.
For the append operation, there is nothing new in the createFile
function that is called in the preceding code (see the preceding examples for the actual code). createFile
calls writeFile
. In writeFile
, you check whether an append operation is requested.
Once you have a FileWriter object, call the seek
method, and pass in the index value for the position where you want to write. In this example, you also test whether the file exists. After calling seek, then call the write method of FileWriter.
Store an existing binary file
We already showed how to write to a file that you just created in the sandboxed file system. What if you need to get access to an existing file and convert that to something you can store on your device? In this example, you obtain a file using an xhr request, and then save it to the cache in the sandboxed file system.
Before you get the file, get a FileSystem reference using requestFileSystem
. By passing window.TEMPORARY in the method call (same as before), the returned FileSystem object (fs) represents the cache in the sandboxed file system. Use fs.root
to get the DirectoryEntry object that you need.
For completeness, here is the xhr request to get a Blob image. There is nothing Cordova-specific in this code, except that you forward the DirectoryEntry reference that you already obtained as an argument to the saveFile function. You will save the blob image and display it later after reading the file (to validate the operation).
For Cordova 5 security, the preceding code requires that you add the domain name, http://cordova.apache.org
, to the Content-Security-Policy element in index.html
.
After getting the file, copy the contents to a new file. The current DirectoryEntry object is already associated with the app cache.
In writeFile, you pass in the Blob object as the dataObj and you will save that in the new file.
After writing to the file, read it and display it. You saved the image as binary data, so you can read it using FileReader.readAsArrayBuffer
.
After reading the data, you can display the image using code like this. Use window.URL.createObjectURL
to get a DOM string for the Blob image.
Display an image file
To display an image using a FileEntry, you can call the toURL
method.
If you are using some platform-specific URIs instead of a FileEntry and you want to display an image, you may need to include the main part of the URI in the Content-Security-Policy element in index.html. Here is an example.
Create Directories
In the code here, you create directories in the root of the app storage location. You could use this code with any writable storage location (that is, any DirectoryEntry). Here, you write to the application cache (assuming that you used window.TEMPORARY to get your FileSystem object) by passing fs.root into this function.
This code creates the /NewDirInRoot/images folder in the application cache. For platform-specific values, look at File System Layouts.
When creating subfolders, you need to create each folder separately as shown in the preceding code.
Last updated