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.

README.md 22 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. ---
  2. title: File Transfer
  3. description: Upload and download files.
  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. |AppVeyor|Travis CI|
  24. |:-:|:-:|
  25. |[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-file-transfer?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-file-transfer)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-file-transfer)|
  26. # cordova-plugin-file-transfer
  27. This plugin allows you to upload and download files.
  28. This plugin defines global `FileTransfer`, `FileUploadOptions` constructors. Although in the global scope, they are not available until after the `deviceready` event.
  29. ```js
  30. document.addEventListener("deviceready", onDeviceReady, false);
  31. function onDeviceReady() {
  32. console.log(FileTransfer);
  33. }
  34. ```
  35. > To get a few ideas, check out the [sample](#sample) at the bottom of this page.
  36. Report issues with this plugin 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%20Transfer%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
  37. ## Deprecated
  38. With the new features introduced in [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), this plugin is not needed any more. Migrating from this plugin to using the new features of [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), is explained in this [Cordova blog post](https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html).
  39. ## Installation
  40. ```bash
  41. cordova plugin add cordova-plugin-file-transfer
  42. ```
  43. ## Supported Platforms
  44. - Amazon Fire OS
  45. - Android
  46. - BlackBerry 10
  47. - Browser
  48. - Firefox OS**
  49. - iOS
  50. - Windows Phone 7 and 8*
  51. - Windows
  52. \* _Do not support `onprogress` nor `abort()`_
  53. \** _Do not support `onprogress`_
  54. # FileTransfer
  55. The `FileTransfer` object provides a way to upload files using an HTTP
  56. multi-part POST or PUT request, and to download files.
  57. ## Properties
  58. - __onprogress__: Called with a `ProgressEvent` whenever a new chunk of data is transferred. _(Function)_
  59. ## Methods
  60. - __upload__: Sends a file to a server.
  61. - __download__: Downloads a file from server.
  62. - __abort__: Aborts an in-progress transfer.
  63. ## upload
  64. __Parameters__:
  65. - __fileURL__: Filesystem URL representing the file on the device or a [data URI](https://en.wikipedia.org/wiki/Data_URI_scheme). For backwards compatibility, this can also be the full path of the file on the device. (See [Backwards Compatibility Notes](#backwards-compatibility-notes) below)
  66. - __server__: URL of the server to receive the file, as encoded by `encodeURI()`.
  67. - __successCallback__: A callback that is passed a `FileUploadResult` object. _(Function)_
  68. - __errorCallback__: A callback that executes if an error occurs retrieving the `FileUploadResult`. Invoked with a `FileTransferError` object. _(Function)_
  69. - __options__: Optional parameters _(Object)_. Valid keys:
  70. - __fileKey__: The name of the form element. Defaults to `file`. (DOMString)
  71. - __fileName__: The file name to use when saving the file on the server. Defaults to `image.jpg`. (DOMString)
  72. - __httpMethod__: The HTTP method to use - either `PUT` or `POST`. Defaults to `POST`. (DOMString)
  73. - __mimeType__: The mime type of the data to upload. Defaults to `image/jpeg`. (DOMString)
  74. - __params__: A set of optional key/value pairs to pass in the HTTP request. (Object, key/value - DOMString)
  75. - __chunkedMode__: Whether to upload the data in chunked streaming mode. Defaults to `true`. (Boolean)
  76. - __headers__: A map of header name/header values. Use a hash to specify one or more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used. (Object)
  77. - __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. Not recommended for production use. Supported on iOS. _(boolean)_
  78. ### Example
  79. ```js
  80. // !! Assumes variable fileURL contains a valid URL to a text file on the device,
  81. // for example, cdvfile://localhost/persistent/path/to/file.txt
  82. var win = function (r) {
  83. console.log("Code = " + r.responseCode);
  84. console.log("Response = " + r.response);
  85. console.log("Sent = " + r.bytesSent);
  86. }
  87. var fail = function (error) {
  88. alert("An error has occurred: Code = " + error.code);
  89. console.log("upload error source " + error.source);
  90. console.log("upload error target " + error.target);
  91. }
  92. var options = new FileUploadOptions();
  93. options.fileKey = "file";
  94. options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
  95. options.mimeType = "text/plain";
  96. var params = {};
  97. params.value1 = "test";
  98. params.value2 = "param";
  99. options.params = params;
  100. var ft = new FileTransfer();
  101. ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
  102. ```
  103. ### Example with Upload Headers and Progress Events (Android and iOS only)
  104. ```js
  105. function win(r) {
  106. console.log("Code = " + r.responseCode);
  107. console.log("Response = " + r.response);
  108. console.log("Sent = " + r.bytesSent);
  109. }
  110. function fail(error) {
  111. alert("An error has occurred: Code = " + error.code);
  112. console.log("upload error source " + error.source);
  113. console.log("upload error target " + error.target);
  114. }
  115. var uri = encodeURI("http://some.server.com/upload.php");
  116. var options = new FileUploadOptions();
  117. options.fileKey="file";
  118. options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
  119. options.mimeType="text/plain";
  120. var headers={'headerParam':'headerValue', 'headerParam2':'headerValue2'};
  121. options.headers = headers;
  122. var ft = new FileTransfer();
  123. ft.onprogress = function(progressEvent) {
  124. if (progressEvent.lengthComputable) {
  125. loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
  126. } else {
  127. loadingStatus.increment();
  128. }
  129. };
  130. ft.upload(fileURL, uri, win, fail, options);
  131. ```
  132. ## FileUploadResult
  133. A `FileUploadResult` object is passed to the success callback of the
  134. `FileTransfer` object's `upload()` method.
  135. ### Properties
  136. - __bytesSent__: The number of bytes sent to the server as part of the upload. (long)
  137. - __responseCode__: The HTTP response code returned by the server. (long)
  138. - __response__: The HTTP response returned by the server. (DOMString)
  139. - __headers__: The HTTP response headers by the server. (Object)
  140. - Currently supported on iOS only.
  141. ### iOS Quirks
  142. - Does not support `responseCode` or `bytesSent`.
  143. - Does not support uploads of an empty file with __chunkedMode=true__ and `multipartMode=false`.
  144. ### Browser Quirks
  145. - __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest
  146. ### Windows Quirks
  147. - An option parameter with empty/null value is excluded in the upload operation due to the Windows API design.
  148. - __chunkedMode__ is not supported and all uploads are set to non-chunked mode.
  149. ## download
  150. __Parameters__:
  151. - __source__: URL of the server to download the file, as encoded by `encodeURI()`.
  152. - __target__: Filesystem url representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device. (See [Backwards Compatibility Notes](#backwards-compatibility-notes) below)
  153. - __successCallback__: A callback that is passed a `FileEntry` object. _(Function)_
  154. - __errorCallback__: A callback that executes if an error occurs when retrieving the `FileEntry`. Invoked with a `FileTransferError` object. _(Function)_
  155. - __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. Not recommended for production use. Supported on iOS. _(boolean)_
  156. - __options__: Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).
  157. ### Example
  158. ```js
  159. // !! Assumes variable fileURL contains a valid URL to a path on the device,
  160. // for example, cdvfile://localhost/persistent/path/to/downloads/
  161. var fileTransfer = new FileTransfer();
  162. var uri = encodeURI("http://some.server.com/download.php");
  163. fileTransfer.download(
  164. uri,
  165. fileURL,
  166. function(entry) {
  167. console.log("download complete: " + entry.toURL());
  168. },
  169. function(error) {
  170. console.log("download error source " + error.source);
  171. console.log("download error target " + error.target);
  172. console.log("download error code" + error.code);
  173. },
  174. false,
  175. {
  176. headers: {
  177. "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
  178. }
  179. }
  180. );
  181. ```
  182. ### WP8 Quirks
  183. - Download requests is being cached by native implementation. To avoid caching, pass `if-Modified-Since` header to download method.
  184. ### Browser Quirks
  185. - __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest
  186. ## abort
  187. Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of `FileTransferError.ABORT_ERR`.
  188. ### Example
  189. ```js
  190. // !! Assumes variable fileURL contains a valid URL to a text file on the device,
  191. // for example, cdvfile://localhost/persistent/path/to/file.txt
  192. var win = function(r) {
  193. console.log("Should not be called.");
  194. }
  195. var fail = function(error) {
  196. // error.code == FileTransferError.ABORT_ERR
  197. alert("An error has occurred: Code = " + error.code);
  198. console.log("upload error source " + error.source);
  199. console.log("upload error target " + error.target);
  200. }
  201. var options = new FileUploadOptions();
  202. options.fileKey="file";
  203. options.fileName="myphoto.jpg";
  204. options.mimeType="image/jpeg";
  205. var ft = new FileTransfer();
  206. ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
  207. ft.abort();
  208. ```
  209. ## FileTransferError
  210. A `FileTransferError` object is passed to an error callback when an error occurs.
  211. ### Properties
  212. - __code__: One of the predefined error codes listed below. (Number)
  213. - __source__: URL to the source. (String)
  214. - __target__: URL to the target. (String)
  215. - __http_status__: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number)
  216. - __body__ Response body. This attribute is only available when a response is received from the HTTP connection. (String)
  217. - __exception__: Either e.getMessage or e.toString (String)
  218. ### iOS Quirks
  219. __exception__ is never defined.
  220. ### Constants
  221. - 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
  222. - 2 = `FileTransferError.INVALID_URL_ERR`
  223. - 3 = `FileTransferError.CONNECTION_ERR`
  224. - 4 = `FileTransferError.ABORT_ERR`
  225. - 5 = `FileTransferError.NOT_MODIFIED_ERR`
  226. ## Windows Quirks
  227. - The plugin implementation is based on [BackgroundDownloader](https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.backgrounddownloader.aspx)/[BackgroundUploader](https://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.backgroundtransfer.backgrounduploader.aspx), which entails the latency issues on Windows devices (creation/starting of an operation can take up to a few seconds). You can use XHR or [HttpClient](https://msdn.microsoft.com/en-us/library/windows/apps/windows.web.http.httpclient.aspx) as a quicker alternative for small downloads.
  228. ## Backwards Compatibility Notes
  229. Previous versions of this plugin would only accept device-absolute-file-paths as the source for uploads, or as the target for downloads. These paths would typically be of the form:
  230. /var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
  231. /storage/emulated/0/path/to/file (Android)
  232. For backwards compatibility, these paths are still accepted, and if your application has recorded paths like these in persistent storage, then they can continue to be used.
  233. These paths were previously exposed in the `fullPath` property of `FileEntry` and `DirectoryEntry` objects returned by the File plugin. New versions of the File plugin however, no longer expose these paths to JavaScript.
  234. If you are upgrading to a new (1.0.0 or newer) version of File, and you have previously been using `entry.fullPath` as arguments to `download()` or `upload()`, then you will need to change your code to use filesystem URLs instead.
  235. `FileEntry.toURL()` and `DirectoryEntry.toURL()` return a filesystem URL of the form:
  236. cdvfile://localhost/persistent/path/to/file
  237. which can be used in place of the absolute file path in both `download()` and `upload()` methods.
  238. ## Sample: Download and Upload Files <a name="sample"></a>
  239. Use the File-Transfer plugin to upload and download files. In these examples, we demonstrate several tasks like:
  240. * [Downloading a binary file to the application cache](#binaryFile)
  241. * [Uploading a file created in your application's root](#uploadFile)
  242. * [Downloading the uploaded file](#downloadFile)
  243. ## Download a Binary File to the application cache <a name="binaryFile"></a>
  244. Use the File plugin with the File-Transfer plugin to provide a target for the files that you download (the target must be a FileEntry object). Before you download the file, create a DirectoryEntry object by using `resolveLocalFileSystemURL` and calling `fs.root` in the success callback. Use the `getFile` method of DirectoryEntry to create the target file.
  245. ```js
  246. window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
  247. console.log('file system open: ' + fs.name);
  248. // Make sure you add the domain name to the Content-Security-Policy <meta> element.
  249. var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
  250. // Parameters passed to getFile create a new file or return the file if it already exists.
  251. fs.root.getFile('downloaded-image.png', { create: true, exclusive: false }, function (fileEntry) {
  252. download(fileEntry, url, true);
  253. }, onErrorCreateFile);
  254. }, onErrorLoadFs);
  255. ```
  256. >*Note* For persistent storage, pass LocalFileSystem.PERSISTENT to requestFileSystem.
  257. When you have the FileEntry object, download the file using the `download` method of the FileTransfer object. The 3rd argument to the `download` function of FileTransfer is the success callback, which you can use to call the app's `readBinaryFile` function. In this code example, the `entry` variable is a new FileEntry object that receives the result of the download operation.
  258. ```js
  259. function download(fileEntry, uri, readBinaryData) {
  260. var fileTransfer = new FileTransfer();
  261. var fileURL = fileEntry.toURL();
  262. fileTransfer.download(
  263. uri,
  264. fileURL,
  265. function (entry) {
  266. console.log("Successful download...");
  267. console.log("download complete: " + entry.toURL());
  268. if (readBinaryData) {
  269. // Read the file...
  270. readBinaryFile(entry);
  271. }
  272. else {
  273. // Or just display it.
  274. displayImageByFileURL(entry);
  275. }
  276. },
  277. function (error) {
  278. console.log("download error source " + error.source);
  279. console.log("download error target " + error.target);
  280. console.log("upload error code" + error.code);
  281. },
  282. null, // or, pass false
  283. {
  284. //headers: {
  285. // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
  286. //}
  287. }
  288. );
  289. }
  290. ```
  291. If you just need to display the image, take the FileEntry to call its toURL() function.
  292. ```js
  293. function displayImageByFileURL(fileEntry) {
  294. var elem = document.getElementById('imageElement');
  295. elem.src = fileEntry.toURL();
  296. }
  297. ```
  298. Depending on your app requirements, you may want to read the file. To support operations with binary files, FileReader supports two methods, `readAsBinaryString` and `readAsArrayBuffer`. In this example, use `readAsArrayBuffer` and pass the FileEntry object to the method. Once you read the file successfully, construct a Blob object using the result of the read.
  299. ```js
  300. function readBinaryFile(fileEntry) {
  301. fileEntry.file(function (file) {
  302. var reader = new FileReader();
  303. reader.onloadend = function() {
  304. console.log("Successful file read: " + this.result);
  305. // displayFileData(fileEntry.fullPath + ": " + this.result);
  306. var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
  307. displayImage(blob);
  308. };
  309. reader.readAsArrayBuffer(file);
  310. }, onErrorReadFile);
  311. }
  312. ```
  313. Once you read the file successfully, you can create a DOM URL string using `createObjectURL`, and then display the image.
  314. ```js
  315. function displayImage(blob) {
  316. // Note: Use window.URL.revokeObjectURL when finished with image.
  317. var objURL = window.URL.createObjectURL(blob);
  318. // Displays image if result is a valid DOM string for an image.
  319. var elem = document.getElementById('imageElement');
  320. elem.src = objURL;
  321. }
  322. ```
  323. As you saw previously, you can call FileEntry.toURL() instead to just display the downloaded image (skip the file read).
  324. ## Upload a File <a name="uploadFile"></a>
  325. When you upload a File using the File-Transfer plugin, use the File plugin to provide files for upload (again, they must be FileEntry objects). Before you can upload anything, create a file for upload using the `getFile` method of DirectoryEntry. In this example, create the file in the application's cache (fs.root). Then call the app's writeFile function so you have some content to upload.
  326. ```js
  327. function onUploadFile() {
  328. window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
  329. console.log('file system open: ' + fs.name);
  330. var fileName = "uploadSource.txt";
  331. var dirEntry = fs.root;
  332. dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
  333. // Write something to the file before uploading it.
  334. writeFile(fileEntry);
  335. }, onErrorCreateFile);
  336. }, onErrorLoadFs);
  337. }
  338. ```
  339. In this example, create some simple content, and then call the app's upload function.
  340. ```js
  341. function writeFile(fileEntry, dataObj) {
  342. // Create a FileWriter object for our FileEntry (log.txt).
  343. fileEntry.createWriter(function (fileWriter) {
  344. fileWriter.onwriteend = function () {
  345. console.log("Successful file write...");
  346. upload(fileEntry);
  347. };
  348. fileWriter.onerror = function (e) {
  349. console.log("Failed file write: " + e.toString());
  350. };
  351. if (!dataObj) {
  352. dataObj = new Blob(['file data to upload'], { type: 'text/plain' });
  353. }
  354. fileWriter.write(dataObj);
  355. });
  356. }
  357. ```
  358. Forward the FileEntry object to the upload function. To perform the actual upload, use the upload function of the FileTransfer object.
  359. ```js
  360. function upload(fileEntry) {
  361. // !! Assumes variable fileURL contains a valid URL to a text file on the device,
  362. var fileURL = fileEntry.toURL();
  363. var success = function (r) {
  364. console.log("Successful upload...");
  365. console.log("Code = " + r.responseCode);
  366. // displayFileData(fileEntry.fullPath + " (content uploaded to server)");
  367. }
  368. var fail = function (error) {
  369. alert("An error has occurred: Code = " + error.code);
  370. }
  371. var options = new FileUploadOptions();
  372. options.fileKey = "file";
  373. options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
  374. options.mimeType = "text/plain";
  375. var params = {};
  376. params.value1 = "test";
  377. params.value2 = "param";
  378. options.params = params;
  379. var ft = new FileTransfer();
  380. // SERVER must be a URL that can handle the request, like
  381. // http://some.server.com/upload.php
  382. ft.upload(fileURL, encodeURI(SERVER), success, fail, options);
  383. };
  384. ```
  385. ## Download the uploaded file <a name="downloadFile"></a>
  386. To download the image you just uploaded, you will need a valid URL that can handle the request, for example, http://some.server.com/download.php. Again, the success handler for the FileTransfer.download method receives a FileEntry object. The main difference here from previous examples is that we call FileReader.readAsText to read the result of the download operation, because we uploaded a file with text content.
  387. ```js
  388. function download(fileEntry, uri) {
  389. var fileTransfer = new FileTransfer();
  390. var fileURL = fileEntry.toURL();
  391. fileTransfer.download(
  392. uri,
  393. fileURL,
  394. function (entry) {
  395. console.log("Successful download...");
  396. console.log("download complete: " + entry.toURL());
  397. readFile(entry);
  398. },
  399. function (error) {
  400. console.log("download error source " + error.source);
  401. console.log("download error target " + error.target);
  402. console.log("upload error code" + error.code);
  403. },
  404. null, // or, pass false
  405. {
  406. //headers: {
  407. // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
  408. //}
  409. }
  410. );
  411. }
  412. ```
  413. In the readFile function, call the `readAsText` method of the FileReader object.
  414. ```js
  415. function readFile(fileEntry) {
  416. fileEntry.file(function (file) {
  417. var reader = new FileReader();
  418. reader.onloadend = function () {
  419. console.log("Successful file read: " + this.result);
  420. // displayFileData(fileEntry.fullPath + ": " + this.result);
  421. };
  422. reader.readAsText(file);
  423. }, onErrorReadFile);
  424. }
  425. ```