Merge branch 'fixed-cookies' of https://github.com/dpogue/cordova-plugin-file-transfer
diff --git a/.travis.yml b/.travis.yml
index 2dd75d2..fa7ae7d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,8 +6,8 @@
install:
- echo -e "Host github.com\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
- cd ..
- - npm install -g purplecabbage/cordova-paramedic
+ - npm install -g cordova-paramedic
- npm install -g cordova
- npm install -g ios-sim
script:
- - cordova-paramedic --platform ios --plugin ../cordova-plugin-file-transfer
+ - cordova-paramedic --platform ios --plugin ${TRAVIS_BUILD_DIR}
diff --git a/README.md b/README.md
index 8504353..7605ce3 100644
--- a/README.md
+++ b/README.md
@@ -1,24 +1,305 @@
-<!---
- license: Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
+<!--
+# license: Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
-->
-
-# org.apache.cordova.file-transfer
+
+# cordova-plugin-file-transfer
[![Build Status](https://travis-ci.org/apache/cordova-plugin-file-transfer.svg)](https://travis-ci.org/apache/cordova-plugin-file-transfer)
Plugin documentation: [doc/index.md](doc/index.md)
+
+This plugin allows you to upload and download files.
+
+This plugin defines global `FileTransfer`, `FileUploadOptions` Constructors.
+
+Although in the global scope, they are not available until after the `deviceready` event.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+## Installation
+
+ cordova plugin add cordova-plugin-file-transfer
+
+## Supported Platforms
+
+- Amazon Fire OS
+- Android
+- BlackBerry 10
+- Browser
+- Firefox OS**
+- iOS
+- Windows Phone 7 and 8*
+- Windows 8
+- Windows
+
+\* _Do not support `onprogress` nor `abort()`_
+
+\** _Do not support `onprogress`_
+
+# FileTransfer
+
+The `FileTransfer` object provides a way to upload files using an HTTP
+multi-part POST request, and to download files as well.
+
+## Properties
+
+- __onprogress__: Called with a `ProgressEvent` whenever a new chunk of data is transferred. _(Function)_
+
+## Methods
+
+- __upload__: sends a file to a server.
+
+- __download__: downloads a file from server.
+
+- __abort__: Aborts an in-progress transfer.
+
+
+## upload
+
+__Parameters__:
+
+- __fileURL__: 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] below)
+
+- __server__: URL of the server to receive the file, as encoded by `encodeURI()`.
+
+- __successCallback__: A callback that is passed a `FileUploadResult` object. _(Function)_
+
+- __errorCallback__: A callback that executes if an error occurs retrieving the `FileUploadResult`. Invoked with a `FileTransferError` object. _(Function)_
+
+- __options__: Optional parameters _(Object)_. Valid keys:
+ - __fileKey__: The name of the form element. Defaults to `file`. (DOMString)
+ - __fileName__: The file name to use when saving the file on the server. Defaults to `image.jpg`. (DOMString)
+ - __httpMethod__: The HTTP method to use - either `PUT` or `POST`. Defaults to `POST`. (DOMString)
+ - __mimeType__: The mime type of the data to upload. Defaults to `image/jpeg`. (DOMString)
+ - __params__: A set of optional key/value pairs to pass in the HTTP request. (Object)
+ - __chunkedMode__: Whether to upload the data in chunked streaming mode. Defaults to `true`. (Boolean)
+ - __headers__: A map of header name/header values. Use an array to specify more than one value. (Object)
+
+- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. _(boolean)_
+
+### Example
+
+ // !! Assumes variable fileURL contains a valid URL to a text file on the device,
+ // for example, cdvfile://localhost/persistent/path/to/file.txt
+
+ var win = function (r) {
+ console.log("Code = " + r.responseCode);
+ console.log("Response = " + r.response);
+ console.log("Sent = " + r.bytesSent);
+ }
+
+ var fail = function (error) {
+ alert("An error has occurred: Code = " + error.code);
+ console.log("upload error source " + error.source);
+ console.log("upload error target " + error.target);
+ }
+
+ var options = new FileUploadOptions();
+ options.fileKey = "file";
+ options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
+ options.mimeType = "text/plain";
+
+ var params = {};
+ params.value1 = "test";
+ params.value2 = "param";
+
+ options.params = params;
+
+ var ft = new FileTransfer();
+ ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
+
+### Example with Upload Headers and Progress Events (Android and iOS only)
+
+ function win(r) {
+ console.log("Code = " + r.responseCode);
+ console.log("Response = " + r.response);
+ console.log("Sent = " + r.bytesSent);
+ }
+
+ function fail(error) {
+ alert("An error has occurred: Code = " + error.code);
+ console.log("upload error source " + error.source);
+ console.log("upload error target " + error.target);
+ }
+
+ var uri = encodeURI("http://some.server.com/upload.php");
+
+ var options = new FileUploadOptions();
+ options.fileKey="file";
+ options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
+ options.mimeType="text/plain";
+
+ var headers={'headerParam':'headerValue'};
+
+ options.headers = headers;
+
+ var ft = new FileTransfer();
+ ft.onprogress = function(progressEvent) {
+ if (progressEvent.lengthComputable) {
+ loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
+ } else {
+ loadingStatus.increment();
+ }
+ };
+ ft.upload(fileURL, uri, win, fail, options);
+
+## FileUploadResult
+
+A `FileUploadResult` object is passed to the success callback of the
+`FileTransfer` object's `upload()` method.
+
+### Properties
+
+- __bytesSent__: The number of bytes sent to the server as part of the upload. (long)
+
+- __responseCode__: The HTTP response code returned by the server. (long)
+
+- __response__: The HTTP response returned by the server. (DOMString)
+
+- __headers__: The HTTP response headers by the server. (Object)
+ - Currently supported on iOS only.
+
+### iOS Quirks
+
+- Does not support `responseCode` or `bytesSent`.
+
+
+## download
+
+__Parameters__:
+
+- __source__: URL of the server to download the file, as encoded by `encodeURI()`.
+
+- __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] below)
+
+- __successCallback__: A callback that is passed a `FileEntry` object. _(Function)_
+
+- __errorCallback__: A callback that executes if an error occurs when retrieving the `FileEntry`. Invoked with a `FileTransferError` object. _(Function)_
+
+- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. This is useful because Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. _(boolean)_
+
+- __options__: Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).
+
+### Example
+
+ // !! Assumes variable fileURL contains a valid URL to a path on the device,
+ // for example, cdvfile://localhost/persistent/path/to/downloads/
+
+ var fileTransfer = new FileTransfer();
+ var uri = encodeURI("http://some.server.com/download.php");
+
+ fileTransfer.download(
+ uri,
+ fileURL,
+ function(entry) {
+ console.log("download complete: " + entry.toURL());
+ },
+ function(error) {
+ console.log("download error source " + error.source);
+ console.log("download error target " + error.target);
+ console.log("upload error code" + error.code);
+ },
+ false,
+ {
+ headers: {
+ "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
+ }
+ }
+ );
+
+### WP8 Quirks
+
+- Download requests is being cached by native implementation. To avoid caching, pass `if-Modified-Since` header to download method.
+
+## abort
+
+Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.
+
+### Example
+
+ // !! Assumes variable fileURL contains a valid URL to a text file on the device,
+ // for example, cdvfile://localhost/persistent/path/to/file.txt
+
+ var win = function(r) {
+ console.log("Should not be called.");
+ }
+
+ var fail = function(error) {
+ // error.code == FileTransferError.ABORT_ERR
+ alert("An error has occurred: Code = " + error.code);
+ console.log("upload error source " + error.source);
+ console.log("upload error target " + error.target);
+ }
+
+ var options = new FileUploadOptions();
+ options.fileKey="file";
+ options.fileName="myphoto.jpg";
+ options.mimeType="image/jpeg";
+
+ var ft = new FileTransfer();
+ ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
+ ft.abort();
+
+
+## FileTransferError
+
+A `FileTransferError` object is passed to an error callback when an error occurs.
+
+### Properties
+
+- __code__: One of the predefined error codes listed below. (Number)
+
+- __source__: URL to the source. (String)
+
+- __target__: URL to the target. (String)
+
+- __http_status__: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number)
+
+- __body__ Response body. This attribute is only available when a response is received from the HTTP connection. (String)
+
+- __exception__: Either e.getMessage or e.toString (String)
+
+### Constants
+
+- 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+- 2 = `FileTransferError.INVALID_URL_ERR`
+- 3 = `FileTransferError.CONNECTION_ERR`
+- 4 = `FileTransferError.ABORT_ERR`
+- 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Backwards Compatibility Notes
+
+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
+
+ /var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+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.
+
+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.
+
+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.
+
+`FileEntry.toURL()` and `DirectoryEntry.toURL()` return a filesystem URL of the form
+
+ cdvfile://localhost/persistent/path/to/file
+
+which can be used in place of the absolute file path in both `download()` and `upload()` methods.
diff --git a/RELEASENOTES.md b/RELEASENOTES.md
index 40a4ccf..fe2dd8f 100644
--- a/RELEASENOTES.md
+++ b/RELEASENOTES.md
@@ -157,3 +157,39 @@
* Error callback should always be called with the FileTransferError object, and not just the code
* windows: alias appData to Windows.Storage.ApplicationData.current
* CB-8093 Fixes incorrect FileTransferError returned in case of download failure
+
+### 1.0.0 (Apr 15, 2015)
+* CB-8746 bumped version of file dependency
+* CB-8746 gave plugin major version bump
+* CB-8641 Fixed tests to pass on windows and wp8
+* CB-8583 Forces download to overwrite existing target file
+* CB-8589 Fixes upload failure when server's response doesn't contain any data
+* CB-8747 updated dependency, added peer dependency
+* CB-8683 changed plugin-id to pacakge-name
+* CB-8653 properly updated translated docs to use new id
+* CB-8653 updated translated docs to use new id
+* Use TRAVIS_BUILD_DIR, install paramedic by npm
+* CB-8653 Updated Readme
+* CB-8654 Note WP8 download requests caching in docs
+* CB-8590 (Windows) Fixed download.onprogress.lengthComputable
+* CB-8566 Integrate TravisCI
+* CB-8438 cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer
+* CB-8538 Added package.json file
+* CB-8495 Fixed wp8 and wp81 test failures
+* CB-7957 Adds support for `browser` platform
+* CB-8429 Updated version and RELEASENOTES.md for release 0.5.0 (take 2)
+* Fixes typo, introduced in https://github.com/apache/cordova-plugin-file-transfer/commit/bc43b46
+* CB-8407 Use File proxy to construct valid FileEntry for download success callback
+* CB-8407 Removes excess path to native path conversion in download method
+* CB-8429 Updated version and RELEASENOTES.md for release 0.5.0
+* CB-7957 Adds support for `browser` platform
+* CB-8095 Fixes JSHint and formatting issues
+* CB-8095 Updates tests and documentation
+* CB-8095 Rewrite upload method to support progress events properly
+* android: Fix error reporting for unknown uri type on sourceUri instead of targetUri
+
+### 1.1.0 (May 06, 2015)
+* CB-8951 Fixed crash related to headers parsing on **wp8**
+* CB-8933 Increased download and upload test timeout
+* CB-6313 **wp8**: Extra boundary in upload
+* CB-8761 **wp8**: Copy cookies from WebBrowser
diff --git a/doc/de/index.md b/doc/de/index.md
index 429911e..4081503 100644
--- a/doc/de/index.md
+++ b/doc/de/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
Dieses Plugin ermöglicht Ihnen zum Hochladen und Herunterladen von Dateien.
@@ -33,7 +33,7 @@
## Installation
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## Unterstützte Plattformen
@@ -299,4 +299,4 @@
cdvfile://localhost/persistent/path/to/file
-die anstelle der absoluten Dateipfad in `download()` und `upload()` Methode verwendet werden kann.
\ No newline at end of file
+die anstelle der absoluten Dateipfad in `download()` und `upload()` Methode verwendet werden kann.
diff --git a/doc/es/index.md b/doc/es/index.md
index baa5fa3..981c991 100644
--- a/doc/es/index.md
+++ b/doc/es/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
Este plugin te permite cargar y descargar archivos.
@@ -31,7 +31,7 @@
## Instalación
- Cordova plugin añade org.apache.cordova.file-transferencia
+ Cordova plugin añade cordova-plugin-file-transferencia
## Plataformas soportadas
@@ -259,4 +259,4 @@
cdvfile://localhost/persistent/path/to/file
-que puede ser utilizado en lugar de la ruta del archivo absoluta tanto en `download()` y `upload()` los métodos.
\ No newline at end of file
+que puede ser utilizado en lugar de la ruta del archivo absoluta tanto en `download()` y `upload()` los métodos.
diff --git a/doc/fr/index.md b/doc/fr/index.md
index 078f7c1..6b2bce0 100644
--- a/doc/fr/index.md
+++ b/doc/fr/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
Ce plugin vous permet de télécharger des fichiers.
@@ -31,7 +31,7 @@
## Installation
- Cordova plugin ajouter org.apache.cordova.file-transfert
+ Cordova plugin ajouter cordova-plugin-file-transfert
## Plates-formes prises en charge
@@ -258,4 +258,4 @@
cdvfile://localhost/persistent/path/to/file
-qui peut être utilisé à la place le chemin d'accès absolu au fichier dans les deux `download()` et `upload()` méthodes.
\ No newline at end of file
+qui peut être utilisé à la place le chemin d'accès absolu au fichier dans les deux `download()` et `upload()` méthodes.
diff --git a/doc/index.md b/doc/index.md
deleted file mode 100644
index 4c2236b..0000000
--- a/doc/index.md
+++ /dev/null
@@ -1,297 +0,0 @@
-<!---
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-
-# org.apache.cordova.file-transfer
-
-This plugin allows you to upload and download files.
-
-This plugin defines global `FileTransfer`, `FileUploadOptions` Constructors.
-
-Although in the global scope, they are not available until after the `deviceready` event.
-
- document.addEventListener("deviceready", onDeviceReady, false);
- function onDeviceReady() {
- console.log(FileTransfer);
- }
-
-## Installation
-
- cordova plugin add org.apache.cordova.file-transfer
-
-## Supported Platforms
-
-- Amazon Fire OS
-- Android
-- BlackBerry 10
-- Browser
-- Firefox OS**
-- iOS
-- Windows Phone 7 and 8*
-- Windows 8
-- Windows
-
-\* _Do not support `onprogress` nor `abort()`_
-
-\** _Do not support `onprogress`_
-
-# FileTransfer
-
-The `FileTransfer` object provides a way to upload files using an HTTP
-multi-part POST request, and to download files as well.
-
-## Properties
-
-- __onprogress__: Called with a `ProgressEvent` whenever a new chunk of data is transferred. _(Function)_
-
-## Methods
-
-- __upload__: sends a file to a server.
-
-- __download__: downloads a file from server.
-
-- __abort__: Aborts an in-progress transfer.
-
-
-## upload
-
-__Parameters__:
-
-- __fileURL__: 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] below)
-
-- __server__: URL of the server to receive the file, as encoded by `encodeURI()`.
-
-- __successCallback__: A callback that is passed a `FileUploadResult` object. _(Function)_
-
-- __errorCallback__: A callback that executes if an error occurs retrieving the `FileUploadResult`. Invoked with a `FileTransferError` object. _(Function)_
-
-- __options__: Optional parameters _(Object)_. Valid keys:
- - __fileKey__: The name of the form element. Defaults to `file`. (DOMString)
- - __fileName__: The file name to use when saving the file on the server. Defaults to `image.jpg`. (DOMString)
- - __httpMethod__: The HTTP method to use - either `PUT` or `POST`. Defaults to `POST`. (DOMString)
- - __mimeType__: The mime type of the data to upload. Defaults to `image/jpeg`. (DOMString)
- - __params__: A set of optional key/value pairs to pass in the HTTP request. (Object)
- - __chunkedMode__: Whether to upload the data in chunked streaming mode. Defaults to `true`. (Boolean)
- - __headers__: A map of header name/header values. Use an array to specify more than one value. (Object)
-
-- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. _(boolean)_
-
-### Example
-
- // !! Assumes variable fileURL contains a valid URL to a text file on the device,
- // for example, cdvfile://localhost/persistent/path/to/file.txt
-
- var win = function (r) {
- console.log("Code = " + r.responseCode);
- console.log("Response = " + r.response);
- console.log("Sent = " + r.bytesSent);
- }
-
- var fail = function (error) {
- alert("An error has occurred: Code = " + error.code);
- console.log("upload error source " + error.source);
- console.log("upload error target " + error.target);
- }
-
- var options = new FileUploadOptions();
- options.fileKey = "file";
- options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
- options.mimeType = "text/plain";
-
- var params = {};
- params.value1 = "test";
- params.value2 = "param";
-
- options.params = params;
-
- var ft = new FileTransfer();
- ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
-
-### Example with Upload Headers and Progress Events (Android and iOS only)
-
- function win(r) {
- console.log("Code = " + r.responseCode);
- console.log("Response = " + r.response);
- console.log("Sent = " + r.bytesSent);
- }
-
- function fail(error) {
- alert("An error has occurred: Code = " + error.code);
- console.log("upload error source " + error.source);
- console.log("upload error target " + error.target);
- }
-
- var uri = encodeURI("http://some.server.com/upload.php");
-
- var options = new FileUploadOptions();
- options.fileKey="file";
- options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
- options.mimeType="text/plain";
-
- var headers={'headerParam':'headerValue'};
-
- options.headers = headers;
-
- var ft = new FileTransfer();
- ft.onprogress = function(progressEvent) {
- if (progressEvent.lengthComputable) {
- loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
- } else {
- loadingStatus.increment();
- }
- };
- ft.upload(fileURL, uri, win, fail, options);
-
-## FileUploadResult
-
-A `FileUploadResult` object is passed to the success callback of the
-`FileTransfer` object's `upload()` method.
-
-### Properties
-
-- __bytesSent__: The number of bytes sent to the server as part of the upload. (long)
-
-- __responseCode__: The HTTP response code returned by the server. (long)
-
-- __response__: The HTTP response returned by the server. (DOMString)
-
-- __headers__: The HTTP response headers by the server. (Object)
- - Currently supported on iOS only.
-
-### iOS Quirks
-
-- Does not support `responseCode` or `bytesSent`.
-
-
-## download
-
-__Parameters__:
-
-- __source__: URL of the server to download the file, as encoded by `encodeURI()`.
-
-- __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] below)
-
-- __successCallback__: A callback that is passed a `FileEntry` object. _(Function)_
-
-- __errorCallback__: A callback that executes if an error occurs when retrieving the `FileEntry`. Invoked with a `FileTransferError` object. _(Function)_
-
-- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. This is useful because Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. _(boolean)_
-
-- __options__: Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).
-
-### Example
-
- // !! Assumes variable fileURL contains a valid URL to a path on the device,
- // for example, cdvfile://localhost/persistent/path/to/downloads/
-
- var fileTransfer = new FileTransfer();
- var uri = encodeURI("http://some.server.com/download.php");
-
- fileTransfer.download(
- uri,
- fileURL,
- function(entry) {
- console.log("download complete: " + entry.toURL());
- },
- function(error) {
- console.log("download error source " + error.source);
- console.log("download error target " + error.target);
- console.log("upload error code" + error.code);
- },
- false,
- {
- headers: {
- "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
- }
- }
- );
-
-## abort
-
-Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.
-
-### Example
-
- // !! Assumes variable fileURL contains a valid URL to a text file on the device,
- // for example, cdvfile://localhost/persistent/path/to/file.txt
-
- var win = function(r) {
- console.log("Should not be called.");
- }
-
- var fail = function(error) {
- // error.code == FileTransferError.ABORT_ERR
- alert("An error has occurred: Code = " + error.code);
- console.log("upload error source " + error.source);
- console.log("upload error target " + error.target);
- }
-
- var options = new FileUploadOptions();
- options.fileKey="file";
- options.fileName="myphoto.jpg";
- options.mimeType="image/jpeg";
-
- var ft = new FileTransfer();
- ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
- ft.abort();
-
-
-## FileTransferError
-
-A `FileTransferError` object is passed to an error callback when an error occurs.
-
-### Properties
-
-- __code__: One of the predefined error codes listed below. (Number)
-
-- __source__: URL to the source. (String)
-
-- __target__: URL to the target. (String)
-
-- __http_status__: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number)
-
-- __body__ Response body. This attribute is only available when a response is received from the HTTP connection. (String)
-
-- __exception__: Either e.getMessage or e.toString (String)
-
-### Constants
-
-- 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
-- 2 = `FileTransferError.INVALID_URL_ERR`
-- 3 = `FileTransferError.CONNECTION_ERR`
-- 4 = `FileTransferError.ABORT_ERR`
-- 5 = `FileTransferError.NOT_MODIFIED_ERR`
-
-## Backwards Compatibility Notes
-
-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
-
- /var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
- /storage/emulated/0/path/to/file (Android)
-
-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.
-
-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.
-
-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.
-
-`FileEntry.toURL()` and `DirectoryEntry.toURL()` return a filesystem URL of the form
-
- cdvfile://localhost/persistent/path/to/file
-
-which can be used in place of the absolute file path in both `download()` and `upload()` methods.
diff --git a/doc/it/index.md b/doc/it/index.md
index f22ad80..e1b74e3 100644
--- a/doc/it/index.md
+++ b/doc/it/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
Questo plugin permette di caricare e scaricare file.
@@ -33,7 +33,7 @@
## Installazione
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## Piattaforme supportate
@@ -299,4 +299,4 @@
cdvfile://localhost/persistent/path/to/file
-che può essere utilizzato al posto del percorso assoluto nei metodi sia `download()` e `upload()`.
\ No newline at end of file
+che può essere utilizzato al posto del percorso assoluto nei metodi sia `download()` e `upload()`.
diff --git a/doc/ja/index.md b/doc/ja/index.md
index 1f20e05..f885b3c 100644
--- a/doc/ja/index.md
+++ b/doc/ja/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
このプラグインは、アップロードし、ファイルをダウンロードすることができます。
@@ -33,7 +33,7 @@
## インストール
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## サポートされているプラットフォーム
@@ -299,4 +299,4 @@
cdvfile://localhost/persistent/path/to/file
-`download()`、`upload()` メソッドの絶対ファイル パスの代わりに使用できます。
\ No newline at end of file
+`download()`、`upload()` メソッドの絶対ファイル パスの代わりに使用できます。
diff --git a/doc/ko/index.md b/doc/ko/index.md
index 6ca8593..a6e39c0 100644
--- a/doc/ko/index.md
+++ b/doc/ko/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
이 플러그인을 사용 하면 업로드 및 다운로드 파일 수 있습니다.
@@ -33,7 +33,7 @@
## 설치
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## 지원 되는 플랫폼
@@ -299,4 +299,4 @@
cdvfile://localhost/persistent/path/to/file
-어떤 `download()` 및 `upload()` 방법에서 절대 파일 경로 대신 사용할 수 있습니다.
\ No newline at end of file
+어떤 `download()` 및 `upload()` 방법에서 절대 파일 경로 대신 사용할 수 있습니다.
diff --git a/doc/pl/index.md b/doc/pl/index.md
index 7cddfaa..ff9b557 100644
--- a/doc/pl/index.md
+++ b/doc/pl/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
Plugin pozwala na przesyłanie i pobieranie plików.
@@ -33,7 +33,7 @@
## Instalacja
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## Obsługiwane platformy
@@ -299,4 +299,4 @@
cdvfile://localhost/persistent/path/to/file
-które mogą być używane zamiast bezwzględna ścieżka zarówno `download()` i `metody upload()` metody.
\ No newline at end of file
+które mogą być używane zamiast bezwzględna ścieżka zarówno `download()` i `metody upload()` metody.
diff --git a/doc/ru/index.md b/doc/ru/index.md
index 3d75d98..cdd5a15 100644
--- a/doc/ru/index.md
+++ b/doc/ru/index.md
@@ -17,13 +17,13 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
Этот плагин позволяет вам загружать и скачивать файлы.
## Установка
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## Поддерживаемые платформы
@@ -287,4 +287,4 @@
cdvfile://localhost/persistent/path/to/file
-которые могут быть использованы вместо абсолютного пути в обоих `download()` и `upload()` методы.
\ No newline at end of file
+которые могут быть использованы вместо абсолютного пути в обоих `download()` и `upload()` методы.
diff --git a/doc/zh/index.md b/doc/zh/index.md
index e7801f4..b3af1eb 100644
--- a/doc/zh/index.md
+++ b/doc/zh/index.md
@@ -17,7 +17,7 @@
under the License.
-->
-# org.apache.cordova.file-transfer
+# cordova-plugin-file-transfer
這個外掛程式允許你上傳和下載檔案。
@@ -33,7 +33,7 @@
## 安裝
- cordova plugin add org.apache.cordova.file-transfer
+ cordova plugin add cordova-plugin-file-transfer
## 支援的平臺
@@ -299,4 +299,4 @@
cdvfile://localhost/persistent/path/to/file
-它可以用在 `download()` 和 `upload()` 兩種方法中的絕對檔路徑位置。
\ No newline at end of file
+它可以用在 `download()` 和 `upload()` 兩種方法中的絕對檔路徑位置。
diff --git a/package.json b/package.json
index 36421bd..589eab3 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,9 @@
{
"name": "cordova-plugin-file-transfer",
- "version": "0.5.1-dev",
+ "version": "1.1.1-dev",
"description": "Cordova File Transfer Plugin",
"cordova": {
- "id": "org.apache.cordova.file-transfer",
+ "id": "cordova-plugin-file-transfer",
"platforms": [
"android",
"amazon-fireos",
@@ -39,6 +39,9 @@
"cordova-firefoxos",
"cordova-browser"
],
+ "peerDependencies": {
+ "cordova-plugin-file": ">=2.0.0"
+ },
"author": "Apache Software Foundation",
"license": "Apache 2.0"
}
diff --git a/plugin.xml b/plugin.xml
index 46868cf..f2c39ed 100644
--- a/plugin.xml
+++ b/plugin.xml
@@ -20,8 +20,8 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
- id="org.apache.cordova.file-transfer"
- version="0.5.1-dev">
+ id="cordova-plugin-file-transfer"
+ version="1.2.1-dev">
<name>File Transfer</name>
<description>Cordova File Transfer Plugin</description>
<license>Apache 2.0</license>
@@ -30,7 +30,7 @@
<issue>https://issues.apache.org/jira/browse/CB/component/12320650</issue>
<!-- dependency id="org.apache.cordova.file@1" /-->
- <dependency id="org.apache.cordova.file" version=">=1.0.1" />
+ <dependency id="cordova-plugin-file" version=">=2.0.0" />
<js-module src="www/FileTransferError.js" name="FileTransferError">
<clobbers target="window.FileTransferError" />
diff --git a/src/ubuntu/file-transfer.cpp b/src/ubuntu/file-transfer.cpp
index 9c553eb..5b1adea 100644
--- a/src/ubuntu/file-transfer.cpp
+++ b/src/ubuntu/file-transfer.cpp
@@ -18,7 +18,7 @@
*/
#include "file-transfer.h"
-#include <plugins/org.apache.cordova.file/file.h>
+#include <plugins/cordova-plugin-file/file.h>
#include <cassert>
static void SetHeaders(QNetworkRequest &request, const QVariantMap &headers) {
diff --git a/src/windows/FileTransferProxy.js b/src/windows/FileTransferProxy.js
index 659e5c9..c056839 100644
--- a/src/windows/FileTransferProxy.js
+++ b/src/windows/FileTransferProxy.js
@@ -24,10 +24,10 @@
/*global module, require*/
var FTErr = require('./FileTransferError'),
- ProgressEvent = require('org.apache.cordova.file.ProgressEvent'),
- FileUploadResult = require('org.apache.cordova.file.FileUploadResult'),
- FileProxy = require('org.apache.cordova.file.FileProxy'),
- FileEntry = require('org.apache.cordova.file.FileEntry');
+ ProgressEvent = require('cordova-plugin-file.ProgressEvent'),
+ FileUploadResult = require('cordova-plugin-file.FileUploadResult'),
+ FileProxy = require('cordova-plugin-file.FileProxy'),
+ FileEntry = require('cordova-plugin-file.FileEntry');
var appData = Windows.Storage.ApplicationData.current;
@@ -161,11 +161,18 @@
}
var response = result.getResponseInformation();
- // creating a data reader, attached to response stream to get server's response
+ var ftResult = new FileUploadResult(result.progress.bytesSent, response.statusCode, '');
+
+ // if server's response doesn't contain any data, then resolve operation now
+ if (result.progress.bytesReceived === 0) {
+ successCallback(ftResult);
+ return;
+ }
+
+ // otherwise create a data reader, attached to response stream to get server's response
var reader = new Windows.Storage.Streams.DataReader(result.getResultStreamAt(0));
- reader.loadAsync(result.progress.bytesReceived).then(function(size) {
- var responseText = reader.readString(size);
- var ftResult = new FileUploadResult(size, response.statusCode, responseText);
+ reader.loadAsync(result.progress.bytesReceived).then(function (size) {
+ ftResult.response = reader.readString(size);
successCallback(ftResult);
reader.close();
});
@@ -268,7 +275,7 @@
fileTransferOps[downloadId] = new FileTransferOperation(FileTransferOperation.PENDING, null);
var downloadCallback = function(storageFolder) {
- storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).then(function(storageFile) {
+ storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(function(storageFile) {
// check if download isn't already cancelled
var downloadOp = fileTransferOps[downloadId];
@@ -312,7 +319,7 @@
var nativeURI = storageFile.path.replace(appData.localFolder.path, 'ms-appdata:///local')
.replace(appData.temporaryFolder.path, 'ms-appdata:///temp')
- .replace('\\', '/');
+ .replace(/\\/g, '/');
// Passing null as error callback here because downloaded file should exist in any case
// otherwise the error callback will be hit during file creation in another place
diff --git a/src/wp/FileTransfer.cs b/src/wp/FileTransfer.cs
index 11db284..0392d1c 100644
--- a/src/wp/FileTransfer.cs
+++ b/src/wp/FileTransfer.cs
@@ -12,15 +12,19 @@
limitations under the License.
*/
+using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
+using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Windows;
using System.Security;
using System.Diagnostics;
+using System.Threading.Tasks;
+using WPCordovaClassLib.Cordova.JSON;
namespace WPCordovaClassLib.Cordova.Commands
{
@@ -86,6 +90,12 @@
private static Dictionary<string, DownloadRequestState> InProcDownloads = new Dictionary<string,DownloadRequestState>();
+ // Private instance of the main WebBrowser instance
+ // NOTE: Any access to this object needs to occur on the UI thread via the Dispatcher
+ private WebBrowser browser;
+
+
+
/// <summary>
/// Uploading response info
/// </summary>
@@ -210,6 +220,106 @@
}
/// <summary>
+ /// Represents a request header passed from Javascript to upload/download operations
+ /// </summary>
+ [DataContract]
+ protected struct Header
+ {
+ [DataMember(Name = "name")]
+ public string Name;
+
+ [DataMember(Name = "value")]
+ public string Value;
+ }
+
+ protected static bool HasJsonDotNet = false;
+ public FileTransfer()
+ {
+ // look for Newtonsoft.Json availability
+ foreach(System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() )
+ {
+ if (assembly.GetType("Newtonsoft.Json.ConstructorHandling") != null)
+ {
+ FileTransfer.HasJsonDotNet = true;
+ break;
+ }
+ }
+ }
+
+ /// Helper method to copy all relevant cookies from the WebBrowser control into a header on
+ /// the HttpWebRequest
+ /// </summary>
+ /// <param name="browser">The source browser to copy the cookies from</param>
+ /// <param name="webRequest">The destination HttpWebRequest to add the cookie header to</param>
+ /// <returns>Nothing</returns>
+ private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest)
+ {
+ var tcs = new TaskCompletionSource<object>();
+
+ // Accessing WebBrowser needs to happen on the UI thread
+ Deployment.Current.Dispatcher.BeginInvoke(() =>
+ {
+ // Get the WebBrowser control
+ if (this.browser == null)
+ {
+ PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
+ if (frame != null)
+ {
+ PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
+ if (page != null)
+ {
+ CordovaView cView = page.FindName("CordovaView") as CordovaView;
+ if (cView != null)
+ {
+ this.browser = cView.Browser;
+ }
+ }
+ }
+ }
+
+ try
+ {
+ // Only copy the cookies if the scheme and host match (to avoid any issues with secure/insecure cookies)
+ // NOTE: since the returned CookieCollection appears to munge the original cookie's domain value in favor of the actual Source domain,
+ // we can't know for sure whether the cookies would be applicable to any other hosts, so best to play it safe and skip for now.
+ if (this.browser != null && this.browser.Source.IsAbsoluteUri == true &&
+ this.browser.Source.Scheme == webRequest.RequestUri.Scheme && this.browser.Source.Host == webRequest.RequestUri.Host)
+ {
+ string cookieHeader = "";
+ string requestPath = webRequest.RequestUri.PathAndQuery;
+ CookieCollection cookies = this.browser.GetCookies();
+
+ // Iterate over the cookies and add to the header
+ foreach (Cookie cookie in cookies)
+ {
+ // Check that the path is allowed, first
+ // NOTE: Path always seems to be empty for now, even if the cookie has a path set by the server.
+ if (cookie.Path.Length == 0 || requestPath.IndexOf(cookie.Path, StringComparison.InvariantCultureIgnoreCase) == 0)
+ {
+ cookieHeader += cookie.Name + "=" + cookie.Value + "; ";
+ }
+ }
+
+ // Finally, set the header if we found any cookies
+ if (cookieHeader.Length > 0)
+ {
+ webRequest.Headers["Cookie"] = cookieHeader;
+ }
+ }
+ }
+ catch (Exception)
+ {
+ // Swallow the exception
+ }
+
+ // Complete the task
+ tcs.SetResult(Type.Missing);
+ });
+
+ await tcs.Task;
+ }
+
+ /// <summary>
/// Upload options
/// </summary>
//private TransferOptions uploadOptions;
@@ -283,20 +393,36 @@
webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
webRequest.Method = uploadOptions.Method;
- if (!string.IsNullOrEmpty(uploadOptions.Headers))
- {
- Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers);
- foreach (string key in headers.Keys)
- {
- webRequest.Headers[key] = headers[key];
- }
- }
-
DownloadRequestState reqState = new DownloadRequestState();
+ InProcDownloads[uploadOptions.Id] = reqState;
reqState.options = uploadOptions;
reqState.request = webRequest;
- InProcDownloads[uploadOptions.Id] = reqState;
+ try
+ {
+ // Associate cookies with the request
+ // This is an async call, so we need to await it in order to preserve proper control flow
+ Task cookieTask = CopyCookiesFromWebBrowser(webRequest);
+ cookieTask.Wait();
+ }
+ catch (AggregateException ae)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(FileTransfer.ConnectionError, uploadOptions.FilePath, uploadOptions.Server, 0, ae.InnerException.Message)));
+ return;
+ }
+
+ if (!string.IsNullOrEmpty(uploadOptions.Headers))
+ {
+ Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers);
+ if (headers != null)
+ {
+ foreach (string key in headers.Keys)
+ {
+ webRequest.Headers[key] = headers[key];
+ }
+ }
+ }
webRequest.BeginGetRequestStream(uploadCallback, reqState);
}
@@ -311,34 +437,22 @@
{
try
{
- Dictionary<string, string> result = new Dictionary<string, string>();
-
- string temp = jsonHeaders.StartsWith("{") ? jsonHeaders.Substring(1) : jsonHeaders;
- temp = temp.EndsWith("}") ? temp.Substring(0, temp.Length - 1) : temp;
-
- string[] strHeaders = temp.Split(',');
- for (int n = 0; n < strHeaders.Length; n++)
+ if (FileTransfer.HasJsonDotNet)
{
- // we need to use indexOf in order to WP7 compatible
- int splitIndex = strHeaders[n].IndexOf(':');
- if (splitIndex > 0)
- {
- string[] split = new string[2];
- split[0] = strHeaders[n].Substring(0, splitIndex);
- split[1] = strHeaders[n].Substring(splitIndex + 1);
-
- split[0] = JSON.JsonHelper.Deserialize<string>(split[0]);
- split[1] = JSON.JsonHelper.Deserialize<string>(split[1]);
- result[split[0]] = split[1];
- }
+ return JsonHelper.Deserialize<Header[]>(jsonHeaders,true)
+ .ToDictionary(header => header.Name, header => header.Value);
}
- return result;
+ else
+ {
+ return JsonHelper.Deserialize<Header[]>(jsonHeaders)
+ .ToDictionary(header => header.Name, header => header.Value);
+ }
}
catch (Exception)
{
Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders);
}
- return null;
+ return new Dictionary<string, string>();
}
public void download(string options)
@@ -475,6 +589,20 @@
state.request = webRequest;
InProcDownloads[downloadOptions.Id] = state;
+ try
+ {
+ // Associate cookies with the request
+ // This is an async call, so we need to await it in order to preserve proper control flow
+ Task cookieTask = CopyCookiesFromWebBrowser(webRequest);
+ cookieTask.Wait();
+ }
+ catch (AggregateException ae)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(FileTransfer.ConnectionError, downloadOptions.Url, downloadOptions.FilePath, 0, ae.InnerException.Message)));
+ return;
+ }
+
if (!string.IsNullOrEmpty(downloadOptions.Headers))
{
Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
@@ -513,7 +641,7 @@
string id = optionStrings[0];
string callbackId = optionStrings[1];
- if (InProcDownloads.ContainsKey(id))
+ if (id != null && InProcDownloads.ContainsKey(id))
{
DownloadRequestState state = InProcDownloads[id];
if (!state.isCancelled)
@@ -730,7 +858,6 @@
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
}
- requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
diff --git a/tests/plugin.xml b/tests/plugin.xml
index d3c1f8f..4fffc0f 100644
--- a/tests/plugin.xml
+++ b/tests/plugin.xml
@@ -20,8 +20,8 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
- id="org.apache.cordova.file-transfer.tests"
- version="0.5.1-dev">
+ id="cordova-plugin-file-transfer-tests"
+ version="1.1.1-dev">
<name>Cordova File Transfer Plugin Tests</name>
<license>Apache 2.0</license>
diff --git a/tests/tests.js b/tests/tests.js
index 682ccc9..b7146a0 100644
--- a/tests/tests.js
+++ b/tests/tests.js
@@ -28,10 +28,13 @@
exports.defineAutoTests = function () {
// constants
- var GRACE_TIME_DELTA = 300; // in milliseconds
+ var GRACE_TIME_DELTA = 600; // in milliseconds
var DEFAULT_FILESYSTEM_SIZE = 1024*50; //filesystem size in bytes
var UNKNOWN_HOST = "http://foobar.apache.org";
var HEADERS_ECHO = "http://whatheaders.com"; // NOTE: this site is very useful!
+ var DOWNLOAD_TIMEOUT = 2 * 60 * 1000; // download tests sometimes need a higher timeout to complete successfully
+ var UPLOAD_TIMEOUT = 2 * 60 * 1000; // upload tests sometimes need a higher timeout to complete successfully
+ var ABORT_DELAY = 100; // for abort() tests
// config for upload test server
// NOTE:
@@ -111,7 +114,6 @@
function (fileEntry) {
fileEntry.remove(
function () {
- console.log('deleted \'' + name + '\'');
done();
},
function () {
@@ -120,7 +122,6 @@
);
},
function () {
- console.log('no \'' + name + '\' to delete; skipping deletion');
done();
}
);
@@ -132,7 +133,6 @@
fileEntry.createWriter(function (writer) {
writer.onwrite = function () {
- console.log('created test file \'' + name + '\'');
success(fileEntry);
};
@@ -305,7 +305,7 @@
// - 'httpssss://example.com'
// - 'apache.org', with subdomains="true"
// - 'cordova-filetransfer.jitsu.com'
- describe('download', function() {
+ describe('download', function () {
// helpers
var verifyDownload = function (fileEntry) {
@@ -317,6 +317,10 @@
deleteFile(root, fileName, done);
});
+ it('ensures that test file does not exist', function (done) {
+ deleteFile(root, fileName, done);
+ });
+
it('filetransfer.spec.4 should download a file', function (done) {
var fileURL = SERVER + '/robots.txt';
@@ -342,7 +346,7 @@
};
transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it('filetransfer.spec.5 should download a file using http basic auth', function (done) {
@@ -354,7 +358,7 @@
};
transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it('filetransfer.spec.6 should get 401 status on http basic auth failure', function (done) {
@@ -368,8 +372,13 @@
done();
};
- transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
- });
+ transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail, null,
+ {
+ headers: {
+ 'If-Modified-Since': 'Thu, 19 Mar 2015 00:00:00 GMT'
+ }
+ });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.7 should download a file using file:// (when hosted from file://)", function (done) {
@@ -394,7 +403,7 @@
};
transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.8 should download a file using https://", function (done) {
@@ -419,15 +428,17 @@
};
transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.11 should call the error callback on abort()", function (done) {
var fileURL = 'http://cordova.apache.org/downloads/BlueZedEx.mp3';
transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, done);
- transfer.abort();
- });
+ setTimeout(function() {
+ transfer.abort();
+ }, ABORT_DELAY);
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.9 should not leave partial file due to abort", function (done) {
@@ -452,7 +463,7 @@
spyOn(transfer, 'onprogress').and.callThrough();
transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.10 should be stopped by abort() right away", function (done) {
@@ -472,13 +483,15 @@
};
transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
- transfer.abort();
+ setTimeout(function() {
+ transfer.abort();
+ }, ABORT_DELAY);
// call abort() again, after a time greater than the grace period
setTimeout(function () {
expect(transfer.abort).not.toThrow();
}, GRACE_TIME_DELTA);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.12 should get http status on failure", function (done) {
@@ -493,7 +506,7 @@
};
transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.13 should get http body on failure", function (done) {
@@ -511,7 +524,7 @@
};
transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.14 should handle malformed urls", function (done) {
@@ -531,33 +544,19 @@
transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
});
- describe('unknown host:', function () {
- var originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
+ it("filetransfer.spec.15 should handle unknown host", function (done) {
+ var fileURL = UNKNOWN_HOST;
- beforeEach(function() {
- jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
- });
+ var downloadFail = function (error) {
+ expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
+ done();
+ };
- afterEach(function() {
- jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
- });
+ // turn off the onprogress handler
+ transfer.onprogress = function () {};
- it("filetransfer.spec.15 should handle unknown host", function (done) {
-
- var fileURL = UNKNOWN_HOST;
-
- var downloadFail = function (error) {
- expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
- done();
- };
-
- // turn off the onprogress handler
- transfer.onprogress = function () {};
-
- transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
- });
- });
-
+ transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
+ }, 30000);
it("filetransfer.spec.16 should handle bad file path", function (done) {
var fileURL = SERVER;
@@ -580,7 +579,7 @@
};
transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.30 downloaded file entries should have a toNativeURL method", function (done) {
@@ -613,7 +612,7 @@
};
transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
- });
+ }, DOWNLOAD_TIMEOUT);
it("filetransfer.spec.28 (compatibility) should be able to download a file using local paths", function (done) {
@@ -721,7 +720,7 @@
// NOTE: removing uploadOptions cause Android to timeout
transfer.upload(localFilePath, fileURL, uploadWin, unexpectedCallbacks.httpFail, uploadOptions);
- });
+ }, UPLOAD_TIMEOUT);
it("filetransfer.spec.19 should be able to upload a file with http basic auth", function (done) {
@@ -734,7 +733,7 @@
// NOTE: removing uploadOptions cause Android to timeout
transfer.upload(localFilePath, fileURL, uploadWin, unexpectedCallbacks.httpFail, uploadOptions);
- });
+ }, UPLOAD_TIMEOUT);
it("filetransfer.spec.21 should be stopped by abort() right away", function (done) {
@@ -757,15 +756,17 @@
// NOTE: removing uploadOptions cause Android to timeout
transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, uploadOptions);
- transfer.abort();
+ setTimeout(function() {
+ transfer.abort();
+ }, ABORT_DELAY);
setTimeout(function () {
expect(transfer.abort).not.toThrow();
}, GRACE_TIME_DELTA);
};
- writeFile(root, fileName, new Array(10000).join('aborttest!'), fileWin);
- });
+ writeFile(root, fileName, new Array(100000).join('aborttest!'), fileWin);
+ }, UPLOAD_TIMEOUT);
it("filetransfer.spec.22 should get http status and body on failure", function (done) {
@@ -778,7 +779,7 @@
};
transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, uploadOptions);
- });
+ }, UPLOAD_TIMEOUT);
it("filetransfer.spec.24 should handle malformed urls", function (done) {
@@ -804,7 +805,7 @@
};
transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, {});
- });
+ }, 30000); // unknown host may need quite some time on some devices
it("filetransfer.spec.25 should handle missing file", function (done) {
@@ -817,7 +818,7 @@
};
transfer.upload('does_not_exist.txt', fileURL, unexpectedCallbacks.httpWin, uploadFail);
- });
+ }, UPLOAD_TIMEOUT);
it("filetransfer.spec.26 should handle bad file path", function (done) {
@@ -860,7 +861,7 @@
// NOTE: removing uploadOptions cause Android to timeout
transfer.upload(localFilePath, fileURL, uploadWin, unexpectedCallbacks.httpFail, uploadOptions);
- });
+ }, UPLOAD_TIMEOUT);
it("filetransfer.spec.29 (compatibility) should be able to upload a file using local paths", function (done) {
@@ -890,7 +891,7 @@
cordova.exec(function (localPath) {
transfer.upload(localPath, fileURL, uploadWin, unexpectedCallbacks.httpFail, uploadOptions);
}, unsupported, 'File', '_getLocalFilesystemPath', [internalFilePath]);
- });
+ }, UPLOAD_TIMEOUT);
});
});
});
diff --git a/www/FileTransfer.js b/www/FileTransfer.js
index 17fb782..add97da 100644
--- a/www/FileTransfer.js
+++ b/www/FileTransfer.js
@@ -22,7 +22,7 @@
var argscheck = require('cordova/argscheck'),
exec = require('cordova/exec'),
FileTransferError = require('./FileTransferError'),
- ProgressEvent = require('org.apache.cordova.file.ProgressEvent');
+ ProgressEvent = require('cordova-plugin-file.ProgressEvent');
function newProgressEvent(result) {
var pe = new ProgressEvent();
@@ -63,6 +63,20 @@
return header;
}
+function convertHeadersToArray(headers) {
+ var result = [];
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ var headerValue = headers[header];
+ result.push({
+ name: header,
+ value: headerValue.toString()
+ });
+ }
+ }
+ return result;
+}
+
var idCounter = 0;
/**
@@ -125,6 +139,11 @@
}
}
+ if (cordova.platformId === "windowsphone") {
+ headers = headers && convertHeadersToArray(headers);
+ params = params && convertHeadersToArray(params);
+ }
+
var fail = errorCallback && function(e) {
var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
errorCallback(error);
@@ -170,6 +189,10 @@
headers = options.headers || null;
}
+ if (cordova.platformId === "windowsphone" && headers) {
+ headers = convertHeadersToArray(headers);
+ }
+
var win = function(result) {
if (typeof result.lengthComputable != "undefined") {
if (self.onprogress) {
@@ -178,10 +201,10 @@
} else if (successCallback) {
var entry = null;
if (result.isDirectory) {
- entry = new (require('org.apache.cordova.file.DirectoryEntry'))();
+ entry = new (require('cordova-plugin-file.DirectoryEntry'))();
}
else if (result.isFile) {
- entry = new (require('org.apache.cordova.file.FileEntry'))();
+ entry = new (require('cordova-plugin-file.FileEntry'))();
}
entry.isDirectory = result.isDirectory;
entry.isFile = result.isFile;
diff --git a/www/blackberry10/FileTransferProxy.js b/www/blackberry10/FileTransferProxy.js
index 438999a..a363f07 100644
--- a/www/blackberry10/FileTransferProxy.js
+++ b/www/blackberry10/FileTransferProxy.js
@@ -25,7 +25,7 @@
* Register all FileTransfer exec calls to be handled by proxy
*/
-var xhrFileTransfer = require('org.apache.cordova.file-transfer.xhrFileTransfer');
+var xhrFileTransfer = require('cordova-plugin-file-transfer.xhrFileTransfer');
module.exports = {
abort: xhrFileTransfer.abort,
diff --git a/www/blackberry10/xhrFileTransfer.js b/www/blackberry10/xhrFileTransfer.js
index 87c8ec0..7eba7af 100644
--- a/www/blackberry10/xhrFileTransfer.js
+++ b/www/blackberry10/xhrFileTransfer.js
@@ -21,8 +21,8 @@
/*global Blob:false */
var cordova = require('cordova'),
- resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'),
- requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'),
+ resolve = cordova.require('cordova-plugin-file.resolveLocalFileSystemURIProxy'),
+ requestAnimationFrame = cordova.require('cordova-plugin-file.bb10RequestAnimationFrame'),
xhr = {};
function getParentPath(filePath) {