arnaucube
arnaucube/openEventsPlatformAppPublic Self-hosted repository
openEventsPlatformApp/plugins/cordova-plugin-file/README.md
plugins/cordova-plugin-file/README.mdRaw
  1---
  2title: File
  3description: Read/write files on the device.
  4---
  5<!--
  6# license: Licensed to the Apache Software Foundation (ASF) under one
  7#         or more contributor license agreements.  See the NOTICE file
  8#         distributed with this work for additional information
  9#         regarding copyright ownership.  The ASF licenses this file
 10#         to you under the Apache License, Version 2.0 (the
 11#         "License"); you may not use this file except in compliance
 12#         with the License.  You may obtain a copy of the License at
 13#
 14#           http://www.apache.org/licenses/LICENSE-2.0
 15#
 16#         Unless required by applicable law or agreed to in writing,
 17#         software distributed under the License is distributed on an
 18#         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 19#         KIND, either express or implied.  See the License for the
 20#         specific language governing permissions and limitations
 21#         under the License.
 22-->
 23
 24|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
 25|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
 26|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-file/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-file)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-file/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-file.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-file)|
 27
 28# cordova-plugin-file
 29
 30This plugin implements a File API allowing read/write access to files residing on the device.
 31
 32This plugin is based on several specs, including :
 33The HTML5 File API
 34[http://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/)
 35
 36The Directories and System extensions
 37Latest:
 38[http://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)
 39Although most of the plugin code was written when an earlier spec was current:
 40[http://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/)
 41
 42It also implements the FileWriter spec :
 43[http://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html)
 44
 45>*Note* 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.
 46
 47To get a few ideas how to use the plugin, check out the [sample](#sample) at the bottom of this page. For additional examples (browser focused), see the HTML5 Rocks' [FileSystem article.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
 48
 49For an overview of other storage options, refer to Cordova's
 50[storage guide](http://cordova.apache.org/docs/en/latest/cordova/storage/storage.html).
 51
 52This plugin defines global `cordova.file` object.
 53
 54Although in the global scope, it is not available until after the `deviceready` event.
 55
 56    document.addEventListener("deviceready", onDeviceReady, false);
 57    function onDeviceReady() {
 58        console.log(cordova.file);
 59    }
 60
 61Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20File%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
 62
 63## Installation
 64
 65    cordova plugin add cordova-plugin-file
 66
 67## Supported Platforms
 68
 69- Amazon Fire OS
 70- Android
 71- BlackBerry 10
 72- Firefox OS
 73- iOS
 74- OS X
 75- Windows Phone 7 and 8*
 76- Windows 8*
 77- Windows*
 78- Browser
 79
 80\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._
 81
 82## Where to Store Files
 83
 84As of v1.2.0, URLs to important file-system directories are provided.
 85Each URL is in the form _file:///path/to/spot/_, and can be converted to a
 86`DirectoryEntry` using `window.resolveLocalFileSystemURL()`.
 87
 88* `cordova.file.applicationDirectory` - Read-only directory where the application
 89  is installed. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_)
 90
 91* `cordova.file.applicationStorageDirectory` - Root directory of the application's
 92  sandbox; on iOS & windows this location is read-only (but specific subdirectories [like
 93  `/Documents` on iOS or `/localState` on windows] are read-write). All data contained within
 94  is private to the app. (_iOS_, _Android_, _BlackBerry 10_, _OSX_)
 95
 96* `cordova.file.dataDirectory` - Persistent and private data storage within the
 97  application's sandbox using internal memory (on Android, if you need to use
 98  external memory, use `.externalDataDirectory`). On iOS, this directory is not
 99  synced with iCloud (use `.syncedDataDirectory`). (_iOS_, _Android_, _BlackBerry 10_, _windows_)
100
101* `cordova.file.cacheDirectory` -  Directory for cached data files or any files
102  that your app can re-create easily. The OS may delete these files when the device
103  runs low on storage, nevertheless, apps should not rely on the OS to delete files
104  in here. (_iOS_, _Android_, _BlackBerry 10_, _OSX_, _windows_)
105
106* `cordova.file.externalApplicationStorageDirectory` - Application space on
107  external storage. (_Android_)
108
109* `cordova.file.externalDataDirectory` - Where to put app-specific data files on
110  external storage. (_Android_)
111
112* `cordova.file.externalCacheDirectory` - Application cache on external storage.
113  (_Android_)
114
115* `cordova.file.externalRootDirectory` - External storage (SD card) root. (_Android_, _BlackBerry 10_)
116
117* `cordova.file.tempDirectory` - Temp directory that the OS can clear at will. Do not
118  rely on the OS to clear this directory; your app should always remove files as
119  applicable. (_iOS_, _OSX_, _windows_)
120
121* `cordova.file.syncedDataDirectory` - Holds app-specific files that should be synced
122  (e.g. to iCloud). (_iOS_, _windows_)
123
124* `cordova.file.documentsDirectory` - Files private to the app, but that are meaningful
125  to other application (e.g. Office files). Note that for _OSX_ this is the user's `~/Documents` directory. (_iOS_, _OSX_)
126
127* `cordova.file.sharedDirectory` - Files globally available to all applications (_BlackBerry 10_)
128
129## File System Layouts
130
131Although technically an implementation detail, it can be very useful to know how
132the `cordova.file.*` properties map to physical paths on a real device.
133
134### iOS File System Layout
135
136| Device Path                                    | `cordova.file.*`            | `iosExtraFileSystems` | r/w? | persistent? | OS clears | sync | private |
137|:-----------------------------------------------|:----------------------------|:----------------------|:----:|:-----------:|:---------:|:----:|:-------:|
138| `/var/mobile/Applications/<UUID>/`             | applicationStorageDirectory | -                     | r    |     N/A     |     N/A   | N/A  |   Yes   |
139| &nbsp;&nbsp;&nbsp;`appname.app/`               | applicationDirectory        | bundle                | r    |     N/A     |     N/A   | N/A  |   Yes   |
140| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`www/`     | -                           | -                     | r    |     N/A     |     N/A   | N/A  |   Yes   |
141| &nbsp;&nbsp;&nbsp;`Documents/`                 | documentsDirectory          | documents             | r/w  |     Yes     |     No    | Yes  |   Yes   |
142| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | -                           | documents-nosync      | r/w  |     Yes     |     No    | No   |   Yes   |
143| &nbsp;&nbsp;&nbsp;`Library`                    | -                           | library               | r/w  |     Yes     |     No    | Yes? |   Yes   |
144| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | dataDirectory               | library-nosync        | r/w  |     Yes     |     No    | No   |   Yes   |
145| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Cloud/`   | syncedDataDirectory         | -                     | r/w  |     Yes     |     No    | Yes  |   Yes   |
146| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Caches/`  | cacheDirectory              | cache                 | r/w  |     Yes*    |  Yes\*\*\*| No   |   Yes   |
147| &nbsp;&nbsp;&nbsp;`tmp/`                       | tempDirectory               | -                     | r/w  |     No\*\*  |  Yes\*\*\*| No   |   Yes   |
148
149
150  \* Files persist across app restarts and upgrades, but this directory can
151     be cleared whenever the OS desires. Your app should be able to recreate any
152     content that might be deleted.
153
154\*\* Files may persist across app restarts, but do not rely on this behavior. Files
155     are not guaranteed to persist across updates. Your app should remove files from
156     this directory when it is applicable, as the OS does not guarantee when (or even
157     if) these files are removed.
158
159\*\*\* The OS may clear the contents of this directory whenever it feels it is
160     necessary, but do not rely on this. You should clear this directory as
161     appropriate for your application.
162
163### Android File System Layout
164
165| Device Path                                     | `cordova.file.*`            | `AndroidExtraFileSystems` | r/w? | persistent? | OS clears | private |
166|:------------------------------------------------|:----------------------------|:--------------------------|:----:|:-----------:|:---------:|:-------:|
167| `file:///android_asset/`                        | applicationDirectory        | assets                    | r    |     N/A     |     N/A   |   Yes   |
168| `/data/data/<app-id>/`                          | applicationStorageDirectory | -                         | r/w  |     N/A     |     N/A   |   Yes   |
169| &nbsp;&nbsp;&nbsp;`cache`                       | cacheDirectory              | cache                     | r/w  |     Yes     |     Yes\* |   Yes   |
170| &nbsp;&nbsp;&nbsp;`files`                       | dataDirectory               | files                     | r/w  |     Yes     |     No    |   Yes   |
171| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Documents` |                             | documents                 | r/w  |     Yes     |     No    |   Yes   |
172| `<sdcard>/`                                     | externalRootDirectory       | sdcard                    | r/w  |     Yes     |     No    |   No    |
173| &nbsp;&nbsp;&nbsp;`Android/data/<app-id>/`      | externalApplicationStorageDirectory | -                 | r/w  |     Yes     |     No    |   No    |
174| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`cache`     | externalCacheDirectry       | cache-external            | r/w  |     Yes     |     No\*\*|   No    |
175| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`files`     | externalDataDirectory       | files-external            | r/w  |     Yes     |     No    |   No    |
176
177\* The OS may periodically clear this directory, but do not rely on this behavior. Clear
178   the contents of this directory as appropriate for your application. Should a user
179   purge the cache manually, the contents of this directory are removed.
180
181\*\* The OS does not clear this directory automatically; you are responsible for managing
182     the contents yourself. Should the user purge the cache manually, the contents of the
183     directory are removed.
184
185**Note**: If external storage can't be mounted, the `cordova.file.external*`
186properties are `null`.
187
188### BlackBerry 10 File System Layout
189
190| Device Path                                                  | `cordova.file.*`            | r/w? | persistent? | OS clears | private |
191|:-------------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
192| `file:///accounts/1000/appdata/<app id>/`                    | applicationStorageDirectory | r    |     N/A     |     N/A   |   Yes   |
193| &nbsp;&nbsp;&nbsp;`app/native`                               | applicationDirectory        | r    |     N/A     |     N/A   |   Yes   |
194| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/temporary/local__0`   | cacheDirectory              | r/w  |     No      |     Yes   |   Yes   |
195| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/persistent/local__0`  | dataDirectory               | r/w  |     Yes     |     No    |   Yes   |
196| `file:///accounts/1000/removable/sdcard`                     | externalRemovableDirectory  | r/w  |     Yes     |     No    |   No    |
197| `file:///accounts/1000/shared`                               | sharedDirectory             | r/w  |     Yes     |     No    |   No    |
198
199*Note*: When application is deployed to work perimeter, all paths are relative to /accounts/1000-enterprise.
200
201### OS X File System Layout
202
203| Device Path                                      | `cordova.file.*`            | `iosExtraFileSystems` | r/w? |  OS clears | private |
204|:-------------------------------------------------|:----------------------------|:----------------------|:----:|:---------:|:-------:|
205| `/Applications/<appname>.app/`                   | -                           | bundle                | r    |     N/A   |   Yes   |
206| &nbsp;&nbsp;&nbsp;&nbsp;`Content/Resources/`     | applicationDirectory        | -                     | r    |     N/A   |   Yes   |
207| `~/Library/Application Support/<bundle-id>/`     | applicationStorageDirectory | -                     | r/w  |     No    |   Yes   |
208| &nbsp;&nbsp;&nbsp;&nbsp;`files/`                 | dataDirectory               | -                     | r/w  |     No    |   Yes   |
209| `~/Documents/`                                   | documentsDirectory          | documents             | r/w  |     No    |    No   |
210| `~/Library/Caches/<bundle-id>/`                  | cacheDirectory              | cache                 | r/w  |     No    |   Yes   |
211| `/tmp/`                                          | tempDirectory               | -                     | r/w  |    Yes\*  |   Yes   |
212| `/`                                              | rootDirectory               | root                  | r/w  |    No\*\* |    No   |
213
214**Note**: This is the layout for non sandboxed applications. I you enable sandboxing, the `applicationStorageDirectory` will be below ` ~/Library/Containers/<bundle-id>/Data/Library/Application Support`.
215
216\* Files persist across app restarts and upgrades, but this directory can
217     be cleared whenever the OS desires. Your app should be able to recreate any
218     content that might be deleted. You should clear this directory as
219     appropriate for your application.
220
221\*\* Allows access to the entire file system. This is only available for non sandboxed apps.
222
223### Windows File System Layout
224
225| Device Path                                           | `cordova.file.*`            | r/w? | persistent? | OS clears | private |
226|:------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
227| `ms-appdata:///`                                      | applicationDirectory        | r    |     N/A     |     N/A   |   Yes   |
228| &nbsp;&nbsp;&nbsp;`local/`                            | dataDirectory               | r/w  |     Yes     |     No    |   Yes   |
229| &nbsp;&nbsp;&nbsp;`temp/`                             | cacheDirectory              | r/w  |     No      |     Yes\* |   Yes   |
230| &nbsp;&nbsp;&nbsp;`temp/`                             | tempDirectory               | r/w  |     No      |     Yes\* |   Yes   |
231| &nbsp;&nbsp;&nbsp;`roaming/`                          | syncedDataDirectory         | r/w  |     Yes     |     No    |   Yes   |
232
233\* The OS may periodically clear this directory
234
235
236## Android Quirks
237
238### Android Persistent storage location
239
240There are multiple valid locations to store persistent files on an Android
241device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html)
242for an extensive discussion of the various possibilities.
243
244Previous versions of the plugin would choose the location of the temporary and
245persistent files on startup, based on whether the device claimed that the SD
246Card (or equivalent storage partition) was mounted. If the SD Card was mounted,
247or if a large internal storage partition was available (such as on Nexus
248devices,) then the persistent files would be stored in the root of that space.
249This meant that all Cordova apps could see all of the files available on the
250card.
251
252If the SD card was not available, then previous versions would store data under
253`/data/data/<packageId>`, which isolates apps from each other, but may still
254cause data to be shared between users.
255
256It is now possible to choose whether to store files in the internal file
257storage location, or using the previous logic, with a preference in your
258application's `config.xml` file. To do this, add one of these two lines to
259`config.xml`:
260
261    <preference name="AndroidPersistentFileLocation" value="Internal" />
262
263    <preference name="AndroidPersistentFileLocation" value="Compatibility" />
264
265Without this line, the File plugin will use `Internal` as the default. If
266a preference tag is present, and is not one of these values, the application
267will not start.
268
269If your application has previously been shipped to users, using an older (pre-
2703.0.0) version of this plugin, and has stored files in the persistent filesystem,
271then you should set the preference to `Compatibility` if your config.xml does not specify a location for the persistent filesystem. Switching the location to
272"Internal" would mean that existing users who upgrade their application may be
273unable to access their previously-stored files, depending on their device.
274
275If your application is new, or has never previously stored files in the
276persistent filesystem, then the `Internal` setting is generally recommended.
277
278### Slow recursive operations for /android_asset
279
280Listing asset directories is really slow on Android. You can speed it up though, by
281adding `src/android/build-extras.gradle` to the root of your android project (also
282requires cordova-android@4.0.0 or greater).
283
284### Permisson to write to external storage when it's not mounted on Marshmallow
285
286Marshmallow requires the apps to ask for permissions when reading/writing to external locations. By
287[default](http://developer.android.com/guide/topics/data/data-storage.html#filesExternal), your app has permission to write to
288`cordova.file.applicationStorageDirectory` and `cordova.file.externalApplicationStorageDirectory`, and the plugin doesn't request permission
289for these two directories unless external storage is not mounted. However due to a limitation, when external storage is not mounted, it would ask for
290permission to write to `cordova.file.externalApplicationStorageDirectory`.
291
292## iOS Quirks
293
294- `cordova.file.applicationStorageDirectory` is read-only; attempting to store
295  files within the root directory will fail. Use one of the other `cordova.file.*`
296  properties defined for iOS (only `applicationDirectory` and `applicationStorageDirectory` are
297  read-only).
298- `FileReader.readAsText(blob, encoding)`
299  - The `encoding` parameter is not supported, and UTF-8 encoding is always in effect.
300
301### iOS Persistent storage location
302
303There are two valid locations to store persistent files on an iOS device: the
304Documents directory and the Library directory. Previous versions of the plugin
305only ever stored persistent files in the Documents directory. This had the
306side-effect of making all of an application's files visible in iTunes, which
307was often unintended, especially for applications which handle lots of small
308files, rather than producing complete documents for export, which is the
309intended purpose of the directory.
310
311It is now possible to choose whether to store files in the documents or library
312directory, with a preference in your application's `config.xml` file. To do this,
313add one of these two lines to `config.xml`:
314
315    <preference name="iosPersistentFileLocation" value="Library" />
316
317    <preference name="iosPersistentFileLocation" value="Compatibility" />
318
319Without this line, the File plugin will use `Compatibility` as the default. If
320a preference tag is present, and is not one of these values, the application
321will not start.
322
323If your application has previously been shipped to users, using an older (pre-
3241.0) version of this plugin, and has stored files in the persistent filesystem,
325then you should set the preference to `Compatibility`. Switching the location to
326`Library` would mean that existing users who upgrade their application would be
327unable to access their previously-stored files.
328
329If your application is new, or has never previously stored files in the
330persistent filesystem, then the `Library` setting is generally recommended.
331
332## Firefox OS Quirks
333
334The File System API is not natively supported by Firefox OS and is implemented
335as a shim on top of indexedDB.
336
337* Does not fail when removing non-empty directories
338* Does not support metadata for directories
339* Methods `copyTo` and `moveTo` do not support directories
340
341The following data paths are supported:
342* `applicationDirectory` - Uses `xhr` to get local files that are packaged with the app.
343* `dataDirectory` - For persistent app-specific data files.
344* `cacheDirectory` - Cached files that should survive app restarts (Apps should not rely
345on the OS to delete files in here).
346
347## Browser Quirks
348
349### Common quirks and remarks
350- Each browser uses its own sandboxed filesystem. IE and Firefox use IndexedDB as a base.
351All browsers use forward slash as directory separator in a path.
352- Directory entries have to be created successively.
353For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)`
354will fail if dir1 did not exist.
355- The plugin requests user permission to use persistent storage at the application first start.
356- Plugin supports `cdvfile://localhost` (local resources) only. I.e. external resources are not supported via `cdvfile`.
357- The plugin does not follow ["File System API 8.3 Naming restrictions"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
358- Blob and File' `close` function is not supported.
359- `FileSaver` and `BlobBuilder` are not supported by this plugin and don't have stubs.
360- The plugin does not support `requestAllFileSystems`. This function is also missing in the specifications.
361- Entries in directory will not be removed if you use `create: true` flag for existing directory.
362- Files created via constructor are not supported. You should use entry.file method instead.
363- Each browser uses its own form for blob URL references.
364- `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension,
365mediatype in IE is always empty (which is the same as `text-plain` according the specification),
366the mediatype in Firefox is always `application/octet-stream`.
367For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`,
368IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:<mediatype depending on extension of entry name>;base64,YWJjZGVmZw==`.
369- `toInternalURL` returns the path in the form `file:///persistent/path/to/entry` (Firefox, IE).
370Chrome returns the path in the form `cdvfile://localhost/persistent/file`.
371
372### Chrome quirks
373- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to `filePluginIsReady` event.
374Example:
375```javascript
376window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
377```
378You can use `window.isFilePluginReadyRaised` function to check whether event was already raised.
379- window.requestFileSystem TEMPORARY and PERSISTENT filesystem quotas are not limited in Chrome.
380- To increase persistent storage in Chrome you need to call `window.initPersistentFileSystem` method. Persistent storage quota is 5 MB by default.
381- Chrome requires `--allow-file-access-from-files` run argument to support API via `file:///` protocol.
382- `File` object will be not changed if you use flag `{create:true}` when getting an existing `Entry`.
383- events `cancelable` property is set to true in Chrome. This is contrary to the [specification](http://dev.w3.org/2009/dap/file-system/file-writer.html).
384- `toURL` function in Chrome returns `filesystem:`-prefixed path depending on application host.
385For example, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`.
386- `toURL` function result does not contain trailing slash in case of directory entry.
387Chrome resolves directories with slash-trailed urls correctly though.
388- `resolveLocalFileSystemURL` method requires the inbound `url` to have `filesystem` prefix. For example, `url` parameter for `resolveLocalFileSystemURL`
389should be in the form `filesystem:file:///persistent/somefile.txt` as opposed to the form `file:///persistent/somefile.txt` in Android.
390- Deprecated `toNativeURL` function is not supported and does not have a stub.
391- `setMetadata` function is not stated in the specifications and not supported.
392- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) on requesting of a non-existant filesystem.
393- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of PATH_EXISTS_ERR(code: 12) on trying to exclusively create a file or directory, which already exists.
394- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of  NO_MODIFICATION_ALLOWED_ERR(code: 6) on trying to call removeRecursively on the root file system.
395- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) on trying to moveTo directory that does not exist.
396
397### IndexedDB-based impl quirks (Firefox and IE)
398- `.` and `..` are not supported.
399- IE does not support `file:///`-mode; only hosted mode is supported (http://localhost:xxxx).
400- Firefox filesystem size is not limited but each 50MB extension will request a user permission.
401IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation of filesystem without prompting,
402once you hit that level you will be asked if you want to allow it to be increased up to a max of 250mb per site.
403So `size` parameter for `requestFileSystem` function does not affect filesystem in Firefox and IE.
404- `readAsBinaryString` function is not stated in the Specs and not supported in IE and does not have a stub.
405- `file.type` is always null.
406- You should not create entry using DirectoryEntry instance callback result which was deleted.
407Otherwise, you will get a 'hanging entry'.
408- Before you can read a file, which was just written you need to get a new instance of this file.
409- `setMetadata` function, which is not stated in the Specs supports `modificationTime` field change only.
410- `copyTo` and `moveTo` functions do not support directories.
411- Directories metadata is not supported.
412- Both Entry.remove and directoryEntry.removeRecursively don't fail when removing
413non-empty directories - directories being removed are cleaned along with contents instead.
414- `abort` and `truncate` functions are not supported.
415- progress events are not fired. For example, this handler will be not executed:
416```javascript
417writer.onprogress = function() { /*commands*/ };
418```
419
420## Upgrading Notes
421
422In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed,
423to be more in line with the published specification.
424
425Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location
426in the `fullPath` property of `Entry` objects. These paths would typically look like
427
428    /var/mobile/Applications/<application UUID>/Documents/path/to/file  (iOS)
429    /storage/emulated/0/path/to/file                                    (Android)
430
431These paths were also returned by the `toURL()` method of the `Entry` objects.
432
433With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of
434the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry`
435object with a `fullPath` of
436
437    /path/to/file
438
439If your application works with device-absolute-paths, and you previously retrieved those
440paths through the `fullPath` property of `Entry` objects, then you should update your code
441to use `entry.toURL()` instead.
442
443For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a
444device-absolute-path, and will return an `Entry` object corresponding to it, as long as that
445file exists within either the `TEMPORARY` or `PERSISTENT` filesystems.
446
447This has particularly been an issue with the File-Transfer plugin, which previously used
448device-absolute-paths (and can still accept them). It has been updated to work correctly
449with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any
450issues getting that plugin to work with files on the device.
451
452In v1.1.0 the return value of `toURL()` was changed (see [CB-6394](https://issues.apache.org/jira/browse/CB-6394))
453to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use `toInternalURL()` now.
454This method will now return filesystem URLs of the form
455
456    cdvfile://localhost/persistent/path/to/file
457
458which can be used to identify the file uniquely.
459
460## cdvfile protocol
461**Purpose**
462
463`cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file` can be used for platform-independent file paths.
464cdvfile 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`.
465
466__*Note__: See [Where to Store Files](#where-to-store-files), [File System Layouts](#file-system-layouts) and [Configuring the Plugin](#configuring-the-plugin-optional) for more details about available fs roots.
467
468To 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.
469
470You can also use `cdvfile://` paths directly in the DOM, for example:
471```HTML
472<img src="cdvfile://localhost/persistent/img/logo.png" />
473```
474
475__Note__: This method requires following Content Security rules updates:
476* Add `cdvfile:` scheme to `Content-Security-Policy` meta tag of the index page, e.g.:
477  - `<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: `**cdvfile:**` https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">`
478* Add `<access origin="cdvfile://*" />` to `config.xml`.
479
480**Converting cdvfile:// to native path**
481
482```javascript
483resolveLocalFileSystemURL('cdvfile://localhost/temporary/path/to/file.mp4', function(entry) {
484    var nativePath = entry.toURL();
485    console.log('Native URI: ' + nativePath);
486    document.getElementById('video').src = nativePath;
487```
488
489**Converting native path to cdvfile://**
490
491```javascript
492resolveLocalFileSystemURL(nativePath, function(entry) {
493    console.log('cdvfile URI: ' + entry.toInternalURL());
494```
495
496**Using cdvfile in core plugins**
497
498```javascript
499fileTransfer.download(uri, 'cdvfile://localhost/temporary/path/to/file.mp3', function (entry) { ...
500```
501```javascript
502var my_media = new Media('cdvfile://localhost/temporary/path/to/file.mp3', ...);
503my_media.play();
504```
505
506#### cdvfile quirks
507- Using `cdvfile://` paths in the DOM is not supported on Windows platform (a path can be converted to native instead).
508
509
510## List of Error Codes and Meanings
511When an error is thrown, one of the following codes will be used.
512
513| Code | Constant                      |
514|-----:|:------------------------------|
515|    1 | `NOT_FOUND_ERR`               |
516|    2 | `SECURITY_ERR`                |
517|    3 | `ABORT_ERR`                   |
518|    4 | `NOT_READABLE_ERR`            |
519|    5 | `ENCODING_ERR`                |
520|    6 | `NO_MODIFICATION_ALLOWED_ERR` |
521|    7 | `INVALID_STATE_ERR`           |
522|    8 | `SYNTAX_ERR`                  |
523|    9 | `INVALID_MODIFICATION_ERR`    |
524|   10 | `QUOTA_EXCEEDED_ERR`          |
525|   11 | `TYPE_MISMATCH_ERR`           |
526|   12 | `PATH_EXISTS_ERR`             |
527
528## Configuring the Plugin (Optional)
529
530The set of available filesystems can be configured per-platform. Both iOS and
531Android recognize a <preference> tag in `config.xml` which names the
532filesystems to be installed. By default, all file-system roots are enabled.
533
534    <preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
535    <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />
536
537### Android
538
539* `files`: The application's internal file storage directory
540* `files-external`: The application's external file storage directory
541* `sdcard`: The global external file storage directory (this is the root of the SD card, if one is installed). You must have the `android.permission.WRITE_EXTERNAL_STORAGE` permission to use this.
542* `cache`: The application's internal cache directory
543* `cache-external`: The application's external cache directory
544* `assets`: The application's bundle (read-only)
545* `root`: The entire device filesystem
546
547Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
548
549### iOS
550
551* `library`: The application's Library directory
552* `documents`: The application's Documents directory
553* `cache`: The application's Cache directory
554* `bundle`: The application's bundle; the location of the app itself on disk (read-only)
555* `root`: The entire device filesystem
556
557By 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.
558
559## Sample: Create Files and Directories, Write, Read, and Append files <a name="sample"></a>
560
561The 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:
562* [Accessing the file system](#persistent)
563* Using cross-platform Cordova file URLs to [store your files](#appendFile) (see _Where to Store Files_ for more info)
564* Creating [files](#persistent) and [directories](#createDir)
565* [Writing to files](#writeFile)
566* [Reading files](#readFile)
567* [Appending files](#appendFile)
568* [Display an image file](#displayImage)
569
570## Create a persistent file <a name="persistent"></a>
571
572Before 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.
573
574When 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.requestLocalFileSystemURL, which support platform-specific locations. For one example of this, see _Append a File_.)
575
576Here is a request for persistent storage.
577
578>*Note* When targeting WebView clients (instead of a browser) or native apps (Windows), you dont need to use `requestQuota` before using persistent storage.
579
580```js
581window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
582
583    console.log('file system open: ' + fs.name);
584    fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {
585
586        console.log("fileEntry is file?" + fileEntry.isFile.toString());
587        // fileEntry.name == 'someFile.txt'
588        // fileEntry.fullPath == '/someFile.txt'
589        writeFile(fileEntry, null);
590
591    }, onErrorCreateFile);
592
593}, onErrorLoadFs);
594```
595
596The 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.
597
598The success callback for `getFile` receives a FileEntry object. You can use this to perform file write and file read operations.
599
600## Create a temporary file
601
602Here 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.
603
604```js
605window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
606
607    console.log('file system open: ' + fs.name);
608    createFile(fs.root, "newTempFile.txt", false);
609
610}, onErrorLoadFs);
611```
612When 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.
613
614```js
615function createFile(dirEntry, fileName, isAppend) {
616    // Creates a new file or returns the file if it already exists.
617    dirEntry.getFile(fileName, {create: true, exclusive: false}, function(fileEntry) {
618
619        writeFile(fileEntry, null, isAppend);
620
621    }, onErrorCreateFile);
622
623}
624```
625
626## Write to a file <a name="writeFile"></a>
627
628Once 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.
629
630```js
631function writeFile(fileEntry, dataObj) {
632    // Create a FileWriter object for our FileEntry (log.txt).
633    fileEntry.createWriter(function (fileWriter) {
634
635        fileWriter.onwriteend = function() {
636            console.log("Successful file write...");
637            readFile(fileEntry);
638        };
639
640        fileWriter.onerror = function (e) {
641            console.log("Failed file write: " + e.toString());
642        };
643
644        // If data object is not passed in,
645        // create a new Blob instead.
646        if (!dataObj) {
647            dataObj = new Blob(['some file data'], { type: 'text/plain' });
648        }
649
650        fileWriter.write(dataObj);
651    });
652}
653```
654
655## Read a file <a name="readFile"></a>
656
657You 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.
658
659```js
660function readFile(fileEntry) {
661
662    fileEntry.file(function (file) {
663        var reader = new FileReader();
664
665        reader.onloadend = function() {
666            console.log("Successful file read: " + this.result);
667            displayFileData(fileEntry.fullPath + ": " + this.result);
668        };
669
670        reader.readAsText(file);
671
672    }, onErrorReadFile);
673}
674```
675
676## Append a file using alternative methods <a name="appendFile"></a>
677
678Of 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.
679
680```js
681window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) {
682    console.log('file system open: ' + dirEntry.name);
683    var isAppend = true;
684    createFile(dirEntry, "fileToAppend.txt", isAppend);
685}, onErrorLoadFs);
686```
687
688In 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_.
689
690For 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.
691
692Once 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.
693
694```js
695function writeFile(fileEntry, dataObj, isAppend) {
696    // Create a FileWriter object for our FileEntry (log.txt).
697    fileEntry.createWriter(function (fileWriter) {
698
699        fileWriter.onwriteend = function() {
700            console.log("Successful file read...");
701            readFile(fileEntry);
702        };
703
704        fileWriter.onerror = function (e) {
705            console.log("Failed file read: " + e.toString());
706        };
707
708        // If we are appending data to file, go to the end of the file.
709        if (isAppend) {
710            try {
711                fileWriter.seek(fileWriter.length);
712            }
713            catch (e) {
714                console.log("file doesn't exist!");
715            }
716        }
717        fileWriter.write(dataObj);
718    });
719}
720```
721
722## Store an existing binary file <a name="binaryFile"></a>
723
724We 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.
725
726Before 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.
727
728```js
729window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
730
731    console.log('file system open: ' + fs.name);
732    getSampleFile(fs.root);
733
734}, onErrorLoadFs);
735```
736
737For 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).
738
739```js
740function getSampleFile(dirEntry) {
741
742    var xhr = new XMLHttpRequest();
743    xhr.open('GET', 'http://cordova.apache.org/static/img/cordova_bot.png', true);
744    xhr.responseType = 'blob';
745
746    xhr.onload = function() {
747        if (this.status == 200) {
748
749            var blob = new Blob([this.response], { type: 'image/png' });
750            saveFile(dirEntry, blob, "downloadedImage.png");
751        }
752    };
753    xhr.send();
754}
755```
756>*Note* For Cordova 5 security, the preceding code requires that you add the domain name, http://cordova.apache.org, to the Content-Security-Policy <meta> element in index.html.
757
758After getting the file, copy the contents to a new file. The current DirectoryEntry object is already associated with the app cache.
759
760```js
761function saveFile(dirEntry, fileData, fileName) {
762
763    dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
764
765        writeFile(fileEntry, fileData);
766
767    }, onErrorCreateFile);
768}
769```
770
771In writeFile, you pass in the Blob object as the dataObj and you will save that in the new file.
772
773```js
774function writeFile(fileEntry, dataObj, isAppend) {
775
776    // Create a FileWriter object for our FileEntry (log.txt).
777    fileEntry.createWriter(function (fileWriter) {
778
779        fileWriter.onwriteend = function() {
780            console.log("Successful file write...");
781            if (dataObj.type == "image/png") {
782                readBinaryFile(fileEntry);
783            }
784            else {
785                readFile(fileEntry);
786            }
787        };
788
789        fileWriter.onerror = function(e) {
790            console.log("Failed file write: " + e.toString());
791        };
792
793        fileWriter.write(dataObj);
794    });
795}
796```
797
798After writing to the file, read it and display it. You saved the image as binary data, so you can read it using FileReader.readAsArrayBuffer.
799
800```js
801function readBinaryFile(fileEntry) {
802
803    fileEntry.file(function (file) {
804        var reader = new FileReader();
805
806        reader.onloadend = function() {
807
808            console.log("Successful file write: " + this.result);
809            displayFileData(fileEntry.fullPath + ": " + this.result);
810
811            var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
812            displayImage(blob);
813        };
814
815        reader.readAsArrayBuffer(file);
816
817    }, onErrorReadFile);
818}
819```
820
821After 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.
822
823```js
824function displayImage(blob) {
825
826    // Displays image if result is a valid DOM string for an image.
827    var elem = document.getElementById('imageFile');
828    // Note: Use window.URL.revokeObjectURL when finished with image.
829    elem.src = window.URL.createObjectURL(blob);
830}
831```
832
833## Display an image file <a name="displayImage"></a>
834
835To display an image using a FileEntry, you can call the `toURL` method.
836
837```js
838function displayImageByFileURL(fileEntry) {
839    var elem = document.getElementById('imageFile');
840    elem.src = fileEntry.toURL();
841}
842```
843
844If 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 <meta> element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your <meta> element. Here is an example.
845
846```html
847<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
848```
849
850## Create Directories <a name="createDir"></a>
851
852In 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.
853
854This code creates the /NewDirInRoot/images folder in the application cache. For platform-specific values, look at _File System Layouts_.
855
856```js
857function createDirectory(rootDirEntry) {
858    rootDirEntry.getDirectory('NewDirInRoot', { create: true }, function (dirEntry) {
859        dirEntry.getDirectory('images', { create: true }, function (subDirEntry) {
860
861            createFile(subDirEntry, "fileInNewSubDir.txt");
862
863        }, onErrorGetDir);
864    }, onErrorGetDir);
865}
866```
867
868When creating subfolders, you need to create each folder separately as shown in the preceding code.