You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

868 lines
47 KiB

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