diff --git a/package.json b/package.json
index 7f16885..727a0e3 100644
--- a/package.json
+++ b/package.json
@@ -21,7 +21,9 @@
"cordova-plugin-splashscreen",
"cordova-plugin-statusbar",
"ionic-plugin-keyboard",
- "cordova-plugin-inappbrowser"
+ "cordova-plugin-inappbrowser",
+ "cordova-plugin-file",
+ "org.apache.cordova.file-transfer"
],
"cordovaPlatforms": [
"android"
diff --git a/platforms/android/AndroidManifest.xml b/platforms/android/AndroidManifest.xml
index 8b810ac..44d6674 100644
--- a/platforms/android/AndroidManifest.xml
+++ b/platforms/android/AndroidManifest.xml
@@ -14,4 +14,5 @@
+
diff --git a/platforms/android/android.json b/platforms/android/android.json
index ebd9a8d..6074b4f 100644
--- a/platforms/android/android.json
+++ b/platforms/android/android.json
@@ -12,6 +12,12 @@
"xml": " ",
"count": 1
}
+ ],
+ "/*": [
+ {
+ "xml": " ",
+ "count": 2
+ }
]
}
},
@@ -45,6 +51,14 @@
{
"xml": " ",
"count": 1
+ },
+ {
+ "xml": " ",
+ "count": 1
+ },
+ {
+ "xml": " ",
+ "count": 1
}
]
}
@@ -58,6 +72,16 @@
}
]
}
+ },
+ "config.xml": {
+ "parents": {
+ "/*": [
+ {
+ "xml": " ",
+ "count": 1
+ }
+ ]
+ }
}
}
},
@@ -86,6 +110,12 @@
},
"cordova-plugin-inappbrowser": {
"PACKAGE_NAME": "com.raataar.wolle_rosen_kaufen"
+ },
+ "cordova-plugin-file": {
+ "PACKAGE_NAME": "com.raataar.wolle_rosen_kaufen"
+ },
+ "cordova-plugin-file-transfer": {
+ "PACKAGE_NAME": "com.raataar.wolle_rosen_kaufen"
}
},
"dependent_plugins": {},
@@ -145,6 +175,189 @@
"cordova.InAppBrowser.open",
"window.open"
]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
+ "id": "cordova-plugin-file.DirectoryEntry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.DirectoryEntry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
+ "id": "cordova-plugin-file.DirectoryReader",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.DirectoryReader"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Entry.js",
+ "id": "cordova-plugin-file.Entry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Entry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/File.js",
+ "id": "cordova-plugin-file.File",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.File"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",
+ "id": "cordova-plugin-file.FileEntry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileEntry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileError.js",
+ "id": "cordova-plugin-file.FileError",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileError"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileReader.js",
+ "id": "cordova-plugin-file.FileReader",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileReader"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",
+ "id": "cordova-plugin-file.FileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
+ "id": "cordova-plugin-file.FileUploadOptions",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileUploadOptions"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
+ "id": "cordova-plugin-file.FileUploadResult",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileUploadResult"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",
+ "id": "cordova-plugin-file.FileWriter",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileWriter"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Flags.js",
+ "id": "cordova-plugin-file.Flags",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Flags"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
+ "id": "cordova-plugin-file.LocalFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.LocalFileSystem"
+ ],
+ "merges": [
+ "window"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Metadata.js",
+ "id": "cordova-plugin-file.Metadata",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Metadata"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
+ "id": "cordova-plugin-file.ProgressEvent",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.ProgressEvent"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",
+ "id": "cordova-plugin-file.fileSystems",
+ "pluginId": "cordova-plugin-file"
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
+ "id": "cordova-plugin-file.requestFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.requestFileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "window"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",
+ "id": "cordova-plugin-file.androidFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "FileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
+ "id": "cordova-plugin-file.fileSystems-roots",
+ "pluginId": "cordova-plugin-file",
+ "runs": true
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
+ "id": "cordova-plugin-file.fileSystemPaths",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "cordova"
+ ],
+ "runs": true
+ },
+ {
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
+ "id": "cordova-plugin-file-transfer.FileTransferError",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransferError"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
+ "id": "cordova-plugin-file-transfer.FileTransfer",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransfer"
+ ]
}
],
"plugin_metadata": {
@@ -155,6 +368,8 @@
"cordova-plugin-statusbar": "2.0.0",
"cordova-plugin-whitelist": "1.2.0",
"ionic-plugin-keyboard": "1.0.8",
- "cordova-plugin-inappbrowser": "1.1.1"
+ "cordova-plugin-inappbrowser": "1.1.1",
+ "cordova-plugin-file": "3.0.0",
+ "cordova-plugin-file-transfer": "1.4.0"
}
}
\ No newline at end of file
diff --git a/platforms/android/assets/www/cordova_plugins.js b/platforms/android/assets/www/cordova_plugins.js
index d0dae10..e310c63 100644
--- a/platforms/android/assets/www/cordova_plugins.js
+++ b/platforms/android/assets/www/cordova_plugins.js
@@ -55,6 +55,189 @@ module.exports = [
"cordova.InAppBrowser.open",
"window.open"
]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
+ "id": "cordova-plugin-file.DirectoryEntry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.DirectoryEntry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
+ "id": "cordova-plugin-file.DirectoryReader",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.DirectoryReader"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Entry.js",
+ "id": "cordova-plugin-file.Entry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Entry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/File.js",
+ "id": "cordova-plugin-file.File",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.File"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",
+ "id": "cordova-plugin-file.FileEntry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileEntry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileError.js",
+ "id": "cordova-plugin-file.FileError",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileError"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileReader.js",
+ "id": "cordova-plugin-file.FileReader",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileReader"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",
+ "id": "cordova-plugin-file.FileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
+ "id": "cordova-plugin-file.FileUploadOptions",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileUploadOptions"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
+ "id": "cordova-plugin-file.FileUploadResult",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileUploadResult"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",
+ "id": "cordova-plugin-file.FileWriter",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileWriter"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Flags.js",
+ "id": "cordova-plugin-file.Flags",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Flags"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
+ "id": "cordova-plugin-file.LocalFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.LocalFileSystem"
+ ],
+ "merges": [
+ "window"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Metadata.js",
+ "id": "cordova-plugin-file.Metadata",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Metadata"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
+ "id": "cordova-plugin-file.ProgressEvent",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.ProgressEvent"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",
+ "id": "cordova-plugin-file.fileSystems",
+ "pluginId": "cordova-plugin-file"
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
+ "id": "cordova-plugin-file.requestFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.requestFileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "window"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",
+ "id": "cordova-plugin-file.androidFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "FileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
+ "id": "cordova-plugin-file.fileSystems-roots",
+ "pluginId": "cordova-plugin-file",
+ "runs": true
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
+ "id": "cordova-plugin-file.fileSystemPaths",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "cordova"
+ ],
+ "runs": true
+ },
+ {
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
+ "id": "cordova-plugin-file-transfer.FileTransferError",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransferError"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
+ "id": "cordova-plugin-file-transfer.FileTransfer",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransfer"
+ ]
}
];
module.exports.metadata =
@@ -67,7 +250,9 @@ module.exports.metadata =
"cordova-plugin-statusbar": "2.0.0",
"cordova-plugin-whitelist": "1.2.0",
"ionic-plugin-keyboard": "1.0.8",
- "cordova-plugin-inappbrowser": "1.1.1"
+ "cordova-plugin-inappbrowser": "1.1.1",
+ "cordova-plugin-file": "3.0.0",
+ "cordova-plugin-file-transfer": "1.4.0"
}
// BOTTOM OF METADATA
});
\ No newline at end of file
diff --git a/platforms/android/assets/www/index.html b/platforms/android/assets/www/index.html
index b4066a8..387514f 100644
--- a/platforms/android/assets/www/index.html
+++ b/platforms/android/assets/www/index.html
@@ -25,7 +25,7 @@
-
+
diff --git a/platforms/android/assets/www/js/controllers.js b/platforms/android/assets/www/js/controllers.js
index d2641b8..ec6a833 100644
--- a/platforms/android/assets/www/js/controllers.js
+++ b/platforms/android/assets/www/js/controllers.js
@@ -1,25 +1,14 @@
angular.module('starter.controllers', [])
-.controller('DashCtrl', function($scope,$ionicPopup,$http) {
+.controller('DashCtrl', function($scope,$ionicPopup,$http, $localstorage) {
$scope.preis="";
$scope.name="";
$scope.freitext="";
- var showAlert=0;
+ $scope.items=[];
+ $scope.item=[];
$scope.validate = function() {
- showAlert=0;
- if ($scope.name.length < 1){
- showAlert=1;
- }
- if ($scope.freitext.length < 1){
- showAlert=1;
- }
-
- if (showAlert==1){
- $scope.showAlert();
- return;
- }
var link = 'http://api.raataar.de/rosen/vorschau.php';
@@ -31,21 +20,19 @@ angular.module('starter.controllers', [])
};
- $scope.showAlert = function() {
- var alertPopup = $ionicPopup.alert({
- title: 'Uuuupppsssiii',
- template: 'Bitte prüfe deine Eingaben.'
- });
- alertPopup.then(function(res) {
- console.log('Thank you for not eating my delicious ice cream cone');
- });
- };
+ $scope.loaddata = function() {
+ $scope.items=$localstorage.getObject('items');
+ alert(JSON.stringify($scope.items));
+ };
- function buysuccessHandler (result) {
- inappbilling.consumePurchase(successHandler, errorHandler, "3xrose");
- }
+ $scope.savedata = function() {
+ $scope.item={name: $scope.name, freitext: $scope.freitext, rosen: $scope.preis, bild: "test"};
+ alert(JSON.stringify($scope.item));
+ $scope.items.push($scope.item);
+ $localstorage.setObject('items',$scope.items);
+ };
- function successHandler (result) {
+ function successBuyHandler (result) {
var strResult = "";
if(typeof result === 'object') {
strResult = JSON.stringify(result);
@@ -55,16 +42,35 @@ angular.module('starter.controllers', [])
alert("SUCCESS: \r\n"+strResult );
}
- function errorHandler (error) {
+ function successConsumeHandler (result) {
+ var strResult = "";
+ if(typeof result === 'object') {
+ strResult = JSON.stringify(result);
+ } else {
+ strResult = result;
+ }
+ alert("SUCCESS: \r\n"+strResult );
+ }
+
+ function errorBuyHandler (error) {
alert("ERROR: \r\n"+error );
- }
+ }
- $scope.buyAdFree = function() {
+ function errorConsumeHandler (error) {
+ alert("ERROR: \r\n"+error );
+ }
- alert($scope.preis);
+
+ function buysuccessHandler (result) {
+ inappbilling.consumePurchase(successConsumeHandler, errorConsumeHandler, $scope.preis);
+ }
+
+ $scope.buyRose = function() {
+
+ //alert($scope.preis);
if((window.device && device.platform == "Android") && typeof inappbilling !== "undefined") {
- inappbilling.buy(buysuccessHandler, errorHandler,"3xrose");
+ inappbilling.buy(successBuyHandler, errorBuyHandler, $scope.preis);
}
}
diff --git a/platforms/android/assets/www/js/services.js b/platforms/android/assets/www/js/services.js
index 73837bf..ac7c5b6 100644
--- a/platforms/android/assets/www/js/services.js
+++ b/platforms/android/assets/www/js/services.js
@@ -1,50 +1,19 @@
angular.module('starter.services', [])
-.factory('Chats', function() {
- // Might use a resource here that returns a JSON array
-
- // Some fake testing data
- var chats = [{
- id: 0,
- name: 'Ben Sparrow',
- lastText: 'You on your way?',
- face: 'img/ben.png'
- }, {
- id: 1,
- name: 'Max Lynx',
- lastText: 'Hey, it\'s me',
- face: 'img/max.png'
- }, {
- id: 2,
- name: 'Adam Bradleyson',
- lastText: 'I should buy a boat',
- face: 'img/adam.jpg'
- }, {
- id: 3,
- name: 'Perry Governor',
- lastText: 'Look at my mukluks!',
- face: 'img/perry.png'
- }, {
- id: 4,
- name: 'Mike Harrington',
- lastText: 'This is wicked good ice cream.',
- face: 'img/mike.png'
- }];
+.factory('$localstorage', ['$window', function($window) {
return {
- all: function() {
- return chats;
+ set: function(key, value) {
+ $window.localStorage[key] = value;
},
- remove: function(chat) {
- chats.splice(chats.indexOf(chat), 1);
+ get: function(key, defaultValue) {
+ return $window.localStorage[key] || defaultValue;
},
- get: function(chatId) {
- for (var i = 0; i < chats.length; i++) {
- if (chats[i].id === parseInt(chatId)) {
- return chats[i];
- }
- }
- return null;
+ setObject: function(key, value) {
+ $window.localStorage[key] = JSON.stringify(value);
+ },
+ getObject: function(key) {
+ return JSON.parse($window.localStorage[key] || '{}');
}
- };
-});
+ }
+}]);
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file-transfer/www/FileTransfer.js b/platforms/android/assets/www/plugins/cordova-plugin-file-transfer/www/FileTransfer.js
new file mode 100644
index 0000000..ff0e6c9
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file-transfer/www/FileTransfer.js
@@ -0,0 +1,237 @@
+cordova.define("cordova-plugin-file-transfer.FileTransfer", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ FileTransferError = require('./FileTransferError'),
+ ProgressEvent = require('cordova-plugin-file.ProgressEvent');
+
+function newProgressEvent(result) {
+ var pe = new ProgressEvent();
+ pe.lengthComputable = result.lengthComputable;
+ pe.loaded = result.loaded;
+ pe.total = result.total;
+ return pe;
+}
+
+function getUrlCredentials(urlString) {
+ var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
+ credentials = credentialsPattern.exec(urlString);
+
+ return credentials && credentials[1];
+}
+
+function getBasicAuthHeader(urlString) {
+ var header = null;
+
+
+ // This is changed due to MS Windows doesn't support credentials in http uris
+ // so we detect them by regexp and strip off from result url
+ // Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem
+
+ if (window.btoa) {
+ var credentials = getUrlCredentials(urlString);
+ if (credentials) {
+ var authHeader = "Authorization";
+ var authHeaderValue = "Basic " + window.btoa(credentials);
+
+ header = {
+ name : authHeader,
+ value : authHeaderValue
+ };
+ }
+ }
+
+ 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;
+
+/**
+ * FileTransfer uploads a file to a remote server.
+ * @constructor
+ */
+var FileTransfer = function() {
+ this._id = ++idCounter;
+ this.onprogress = null; // optional callback
+};
+
+/**
+* Given an absolute file path, uploads a file on the device to a remote server
+* using a multipart HTTP request.
+* @param filePath {String} Full path of the file on the device
+* @param server {String} URL of the server to receive the file
+* @param successCallback (Function} Callback to be invoked when upload has completed
+* @param errorCallback {Function} Callback to be invoked upon error
+* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
+* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+*/
+FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
+ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
+ // check for options
+ var fileKey = null;
+ var fileName = null;
+ var mimeType = null;
+ var params = null;
+ var chunkedMode = true;
+ var headers = null;
+ var httpMethod = null;
+ var basicAuthHeader = getBasicAuthHeader(server);
+ if (basicAuthHeader) {
+ server = server.replace(getUrlCredentials(server) + '@', '');
+
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ if (options) {
+ fileKey = options.fileKey;
+ fileName = options.fileName;
+ mimeType = options.mimeType;
+ headers = options.headers;
+ httpMethod = options.httpMethod || "POST";
+ if (httpMethod.toUpperCase() == "PUT"){
+ httpMethod = "PUT";
+ } else {
+ httpMethod = "POST";
+ }
+ if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
+ chunkedMode = options.chunkedMode;
+ }
+ if (options.params) {
+ params = options.params;
+ }
+ else {
+ params = {};
+ }
+ }
+
+ 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);
+ };
+
+ var self = this;
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ self.onprogress(newProgressEvent(result));
+ }
+ } else {
+ successCallback && successCallback(result);
+ }
+ };
+ exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+};
+
+/**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ * @param source {String} URL of the server to receive the file
+ * @param target {String} Full path of the file on the device
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ * @param options {FileDownloadOptions} Optional parameters such as headers
+ */
+FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
+ argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
+ var self = this;
+
+ var basicAuthHeader = getBasicAuthHeader(source);
+ if (basicAuthHeader) {
+ source = source.replace(getUrlCredentials(source) + '@', '');
+
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var headers = null;
+ if (options) {
+ headers = options.headers || null;
+ }
+
+ if (cordova.platformId === "windowsphone" && headers) {
+ headers = convertHeadersToArray(headers);
+ }
+
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ return self.onprogress(newProgressEvent(result));
+ }
+ } else if (successCallback) {
+ var entry = null;
+ if (result.isDirectory) {
+ entry = new (require('cordova-plugin-file.DirectoryEntry'))();
+ }
+ else if (result.isFile) {
+ entry = new (require('cordova-plugin-file.FileEntry'))();
+ }
+ entry.isDirectory = result.isDirectory;
+ entry.isFile = result.isFile;
+ entry.name = result.name;
+ entry.fullPath = result.fullPath;
+ entry.filesystem = new FileSystem(result.filesystemName || (result.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
+ entry.nativeURL = result.nativeURL;
+ successCallback(entry);
+ }
+ };
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
+ errorCallback(error);
+ };
+
+ exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);
+};
+
+/**
+ * Aborts the ongoing file transfer on this object. The original error
+ * callback for the file transfer will be called if necessary.
+ */
+FileTransfer.prototype.abort = function() {
+ exec(null, null, 'FileTransfer', 'abort', [this._id]);
+};
+
+module.exports = FileTransfer;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file-transfer/www/FileTransferError.js b/platforms/android/assets/www/plugins/cordova-plugin-file-transfer/www/FileTransferError.js
new file mode 100644
index 0000000..8339c2b
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file-transfer/www/FileTransferError.js
@@ -0,0 +1,43 @@
+cordova.define("cordova-plugin-file-transfer.FileTransferError", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileTransferError
+ * @constructor
+ */
+var FileTransferError = function(code, source, target, status, body, exception) {
+ this.code = code || null;
+ this.source = source || null;
+ this.target = target || null;
+ this.http_status = status || null;
+ this.body = body || null;
+ this.exception = exception || null;
+};
+
+FileTransferError.FILE_NOT_FOUND_ERR = 1;
+FileTransferError.INVALID_URL_ERR = 2;
+FileTransferError.CONNECTION_ERR = 3;
+FileTransferError.ABORT_ERR = 4;
+FileTransferError.NOT_MODIFIED_ERR = 5;
+
+module.exports = FileTransferError;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/DirectoryEntry.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/DirectoryEntry.js
new file mode 100644
index 0000000..464d339
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/DirectoryEntry.js
@@ -0,0 +1,119 @@
+cordova.define("cordova-plugin-file.DirectoryEntry", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var argscheck = require('cordova/argscheck'),
+ utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ Entry = require('./Entry'),
+ FileError = require('./FileError'),
+ DirectoryReader = require('./DirectoryReader');
+
+/**
+ * An interface representing a directory on the file system.
+ *
+ * {boolean} isFile always false (readonly)
+ * {boolean} isDirectory always true (readonly)
+ * {DOMString} name of the directory, excluding the path leading to it (readonly)
+ * {DOMString} fullPath the absolute full path to the directory (readonly)
+ * {FileSystem} filesystem on which the directory resides (readonly)
+ */
+var DirectoryEntry = function(name, fullPath, fileSystem, nativeURL) {
+
+ // add trailing slash if it is missing
+ if ((fullPath) && !/\/$/.test(fullPath)) {
+ fullPath += "/";
+ }
+ // add trailing slash if it is missing
+ if (nativeURL && !/\/$/.test(nativeURL)) {
+ nativeURL += "/";
+ }
+ DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);
+};
+
+utils.extend(DirectoryEntry, Entry);
+
+/**
+ * Creates a new DirectoryReader to read entries from this directory
+ */
+DirectoryEntry.prototype.createReader = function() {
+ return new DirectoryReader(this.toInternalURL());
+};
+
+/**
+ * Creates or looks up a directory
+ *
+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
+ * @param {Flags} options to create or exclusively create the directory
+ * @param {Function} successCallback is called with the new entry
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
+ var fs = this.filesystem;
+ var win = successCallback && function(result) {
+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getDirectory", [this.toInternalURL(), path, options]);
+};
+
+/**
+ * Deletes a directory and all of it's contents
+ *
+ * @param {Function} successCallback is called with no parameters
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(successCallback, fail, "File", "removeRecursively", [this.toInternalURL()]);
+};
+
+/**
+ * Creates or looks up a file
+ *
+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
+ * @param {Flags} options to create or exclusively create the file
+ * @param {Function} successCallback is called with the new entry
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
+ var fs = this.filesystem;
+ var win = successCallback && function(result) {
+ var FileEntry = require('./FileEntry');
+ var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getFile", [this.toInternalURL(), path, options]);
+};
+
+module.exports = DirectoryEntry;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/DirectoryReader.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/DirectoryReader.js
new file mode 100644
index 0000000..921b486
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/DirectoryReader.js
@@ -0,0 +1,75 @@
+cordova.define("cordova-plugin-file.DirectoryReader", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec'),
+ FileError = require('./FileError') ;
+
+/**
+ * An interface that lists the files and directories in a directory.
+ */
+function DirectoryReader(localURL) {
+ this.localURL = localURL || null;
+ this.hasReadEntries = false;
+}
+
+/**
+ * Returns a list of entries from a directory.
+ *
+ * @param {Function} successCallback is called with a list of entries
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
+ // If we've already read and passed on this directory's entries, return an empty list.
+ if (this.hasReadEntries) {
+ successCallback([]);
+ return;
+ }
+ var reader = this;
+ var win = typeof successCallback !== 'function' ? null : function(result) {
+ var retVal = [];
+ for (var i=0; i or
+ * tag. If that is not possible, construct a cdvfile:// URL.
+ */
+Entry.prototype.toURL = function() {
+ if (this.nativeURL) {
+ return this.nativeURL;
+ }
+ // fullPath attribute may contain the full URL in the case that
+ // toInternalURL fails.
+ return this.toInternalURL() || "file://localhost" + this.fullPath;
+};
+
+/**
+ * Backwards-compatibility: In v1.0.0 - 1.0.2, .toURL would only return a
+ * cdvfile:// URL, and this method was necessary to obtain URLs usable by the
+ * webview.
+ * See CB-6051, CB-6106, CB-6117, CB-6152, CB-6199, CB-6201, CB-6243, CB-6249,
+ * and CB-6300.
+ */
+Entry.prototype.toNativeURL = function() {
+ console.log("DEPRECATED: Update your code to use 'toURL'");
+ return this.toURL();
+};
+
+/**
+ * Returns a URI that can be used to identify this entry.
+ *
+ * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
+ * @return uri
+ */
+Entry.prototype.toURI = function(mimeType) {
+ console.log("DEPRECATED: Update your code to use 'toURL'");
+ return this.toURL();
+};
+
+/**
+ * Remove a file or directory. It is an error to attempt to delete a
+ * directory that is not empty. It is an error to attempt to delete a
+ * root directory of a file system.
+ *
+ * @param successCallback {Function} called with no parameters
+ * @param errorCallback {Function} called with a FileError
+ */
+Entry.prototype.remove = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.remove', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(successCallback, fail, "File", "remove", [this.toInternalURL()]);
+};
+
+/**
+ * Look up the parent DirectoryEntry of this entry.
+ *
+ * @param successCallback {Function} called with the parent DirectoryEntry object
+ * @param errorCallback {Function} called with a FileError
+ */
+Entry.prototype.getParent = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.getParent', arguments);
+ var fs = this.filesystem;
+ var win = successCallback && function(result) {
+ var DirectoryEntry = require('./DirectoryEntry');
+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getParent", [this.toInternalURL()]);
+};
+
+module.exports = Entry;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/File.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/File.js
new file mode 100644
index 0000000..47c267b
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/File.js
@@ -0,0 +1,81 @@
+cordova.define("cordova-plugin-file.File", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Constructor.
+ * name {DOMString} name of the file, without path information
+ * fullPath {DOMString} the full path of the file, including the name
+ * type {DOMString} mime type
+ * lastModifiedDate {Date} last modified date
+ * size {Number} size of the file in bytes
+ */
+
+var File = function(name, localURL, type, lastModifiedDate, size){
+ this.name = name || '';
+ this.localURL = localURL || null;
+ this.type = type || null;
+ this.lastModified = lastModifiedDate || null;
+ // For backwards compatibility, store the timestamp in lastModifiedDate as well
+ this.lastModifiedDate = lastModifiedDate || null;
+ this.size = size || 0;
+
+ // These store the absolute start and end for slicing the file.
+ this.start = 0;
+ this.end = this.size;
+};
+
+/**
+ * Returns a "slice" of the file. Since Cordova Files don't contain the actual
+ * content, this really returns a File with adjusted start and end.
+ * Slices of slices are supported.
+ * start {Number} The index at which to start the slice (inclusive).
+ * end {Number} The index at which to end the slice (exclusive).
+ */
+File.prototype.slice = function(start, end) {
+ var size = this.end - this.start;
+ var newStart = 0;
+ var newEnd = size;
+ if (arguments.length) {
+ if (start < 0) {
+ newStart = Math.max(size + start, 0);
+ } else {
+ newStart = Math.min(size, start);
+ }
+ }
+
+ if (arguments.length >= 2) {
+ if (end < 0) {
+ newEnd = Math.max(size + end, 0);
+ } else {
+ newEnd = Math.min(end, size);
+ }
+ }
+
+ var newFile = new File(this.name, this.localURL, this.type, this.lastModified, this.size);
+ newFile.start = this.start + newStart;
+ newFile.end = this.start + newEnd;
+ return newFile;
+};
+
+
+module.exports = File;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileEntry.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileEntry.js
new file mode 100644
index 0000000..981ae7b
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileEntry.js
@@ -0,0 +1,83 @@
+cordova.define("cordova-plugin-file.FileEntry", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ Entry = require('./Entry'),
+ FileWriter = require('./FileWriter'),
+ File = require('./File'),
+ FileError = require('./FileError');
+
+/**
+ * An interface representing a file on the file system.
+ *
+ * {boolean} isFile always true (readonly)
+ * {boolean} isDirectory always false (readonly)
+ * {DOMString} name of the file, excluding the path leading to it (readonly)
+ * {DOMString} fullPath the absolute full path to the file (readonly)
+ * {FileSystem} filesystem on which the file resides (readonly)
+ */
+var FileEntry = function(name, fullPath, fileSystem, nativeURL) {
+ FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);
+};
+
+utils.extend(FileEntry, Entry);
+
+/**
+ * Creates a new FileWriter associated with the file that this FileEntry represents.
+ *
+ * @param {Function} successCallback is called with the new FileWriter
+ * @param {Function} errorCallback is called with a FileError
+ */
+FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
+ this.file(function(filePointer) {
+ var writer = new FileWriter(filePointer);
+
+ if (writer.localURL === null || writer.localURL === "") {
+ errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR));
+ } else {
+ successCallback && successCallback(writer);
+ }
+ }, errorCallback);
+};
+
+/**
+ * Returns a File that represents the current state of the file that this FileEntry represents.
+ *
+ * @param {Function} successCallback is called with the new File object
+ * @param {Function} errorCallback is called with a FileError
+ */
+FileEntry.prototype.file = function(successCallback, errorCallback) {
+ var localURL = this.toInternalURL();
+ var win = successCallback && function(f) {
+ var file = new File(f.name, localURL, f.type, f.lastModifiedDate, f.size);
+ successCallback(file);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getFileMetadata", [localURL]);
+};
+
+
+module.exports = FileEntry;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileError.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileError.js
new file mode 100644
index 0000000..403f73b
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileError.js
@@ -0,0 +1,48 @@
+cordova.define("cordova-plugin-file.FileError", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileError
+ */
+function FileError(error) {
+ this.code = error || null;
+}
+
+// File error codes
+// Found in DOMException
+FileError.NOT_FOUND_ERR = 1;
+FileError.SECURITY_ERR = 2;
+FileError.ABORT_ERR = 3;
+
+// Added by File API specification
+FileError.NOT_READABLE_ERR = 4;
+FileError.ENCODING_ERR = 5;
+FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
+FileError.INVALID_STATE_ERR = 7;
+FileError.SYNTAX_ERR = 8;
+FileError.INVALID_MODIFICATION_ERR = 9;
+FileError.QUOTA_EXCEEDED_ERR = 10;
+FileError.TYPE_MISMATCH_ERR = 11;
+FileError.PATH_EXISTS_ERR = 12;
+
+module.exports = FileError;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileReader.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileReader.js
new file mode 100644
index 0000000..6955e9f
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileReader.js
@@ -0,0 +1,392 @@
+cordova.define("cordova-plugin-file.FileReader", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec'),
+ modulemapper = require('cordova/modulemapper'),
+ utils = require('cordova/utils'),
+ File = require('./File'),
+ FileError = require('./FileError'),
+ ProgressEvent = require('./ProgressEvent'),
+ origFileReader = modulemapper.getOriginalSymbol(window, 'FileReader');
+
+/**
+ * This class reads the mobile device file system.
+ *
+ * For Android:
+ * The root directory is the root of the file system.
+ * To read from the SD card, the file name is "sdcard/my_file.txt"
+ * @constructor
+ */
+var FileReader = function() {
+ this._readyState = 0;
+ this._error = null;
+ this._result = null;
+ this._localURL = '';
+ this._realReader = origFileReader ? new origFileReader() : {};
+};
+
+// States
+FileReader.EMPTY = 0;
+FileReader.LOADING = 1;
+FileReader.DONE = 2;
+
+utils.defineGetter(FileReader.prototype, 'readyState', function() {
+ return this._localURL ? this._readyState : this._realReader.readyState;
+});
+
+utils.defineGetter(FileReader.prototype, 'error', function() {
+ return this._localURL ? this._error: this._realReader.error;
+});
+
+utils.defineGetter(FileReader.prototype, 'result', function() {
+ return this._localURL ? this._result: this._realReader.result;
+});
+
+function defineEvent(eventName) {
+ utils.defineGetterSetter(FileReader.prototype, eventName, function() {
+ return this._realReader[eventName] || null;
+ }, function(value) {
+ this._realReader[eventName] = value;
+ });
+}
+defineEvent('onloadstart'); // When the read starts.
+defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)
+defineEvent('onload'); // When the read has successfully completed.
+defineEvent('onerror'); // When the read has failed (see errors).
+defineEvent('onloadend'); // When the request has completed (either in success or failure).
+defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.
+
+function initRead(reader, file) {
+ // Already loading something
+ if (reader.readyState == FileReader.LOADING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ reader._result = null;
+ reader._error = null;
+ reader._readyState = FileReader.LOADING;
+
+ if (typeof file.localURL == 'string') {
+ reader._localURL = file.localURL;
+ } else {
+ reader._localURL = '';
+ return true;
+ }
+
+ reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader}));
+}
+
+/**
+ * Abort reading file.
+ */
+FileReader.prototype.abort = function() {
+ if (origFileReader && !this._localURL) {
+ return this._realReader.abort();
+ }
+ this._result = null;
+
+ if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) {
+ return;
+ }
+
+ this._readyState = FileReader.DONE;
+
+ // If abort callback
+ if (typeof this.onabort === 'function') {
+ this.onabort(new ProgressEvent('abort', {target:this}));
+ }
+ // If load end callback
+ if (typeof this.onloadend === 'function') {
+ this.onloadend(new ProgressEvent('loadend', {target:this}));
+ }
+};
+
+/**
+ * Read text file.
+ *
+ * @param file {File} File object containing file properties
+ * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
+ */
+FileReader.prototype.readAsText = function(file, encoding) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsText(file, encoding);
+ }
+
+ // Default encoding is UTF-8
+ var enc = encoding ? encoding : "UTF-8";
+ var me = this;
+ var execArgs = [this._localURL, enc, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // Save result
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // null result
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsText", execArgs);
+};
+
+
+/**
+ * Read file and return data as a base64 encoded data url.
+ * A data url is of the form:
+ * data:[][;base64],
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsDataURL = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsDataURL(file);
+ }
+
+ var me = this;
+ var execArgs = [this._localURL, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // Save result
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsDataURL", execArgs);
+};
+
+/**
+ * Read file and return data as a binary data.
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsBinaryString = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsBinaryString(file);
+ }
+
+ var me = this;
+ var execArgs = [this._localURL, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsBinaryString", execArgs);
+};
+
+/**
+ * Read file and return data as a binary data.
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsArrayBuffer = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsArrayBuffer(file);
+ }
+
+ var me = this;
+ var execArgs = [this._localURL, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ if (r instanceof Array) {
+ r = new Uint8Array(r).buffer;
+ }
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsArrayBuffer", execArgs);
+};
+
+module.exports = FileReader;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileSystem.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileSystem.js
new file mode 100644
index 0000000..26639b1
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileSystem.js
@@ -0,0 +1,50 @@
+cordova.define("cordova-plugin-file.FileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var DirectoryEntry = require('./DirectoryEntry');
+
+/**
+ * An interface representing a file system
+ *
+ * @constructor
+ * {DOMString} name the unique name of the file system (readonly)
+ * {DirectoryEntry} root directory of the file system (readonly)
+ */
+var FileSystem = function(name, root) {
+ this.name = name;
+ if (root) {
+ this.root = new DirectoryEntry(root.name, root.fullPath, this, root.nativeURL);
+ } else {
+ this.root = new DirectoryEntry(this.name, '/', this);
+ }
+};
+
+FileSystem.prototype.__format__ = function(fullPath, nativeUrl) {
+ return fullPath;
+};
+
+FileSystem.prototype.toJSON = function() {
+ return "";
+};
+
+module.exports = FileSystem;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileUploadOptions.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileUploadOptions.js
new file mode 100644
index 0000000..9928359
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileUploadOptions.js
@@ -0,0 +1,43 @@
+cordova.define("cordova-plugin-file.FileUploadOptions", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Options to customize the HTTP request used to upload files.
+ * @constructor
+ * @param fileKey {String} Name of file request parameter.
+ * @param fileName {String} Filename to be used by the server. Defaults to image.jpg.
+ * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.
+ * @param params {Object} Object with key: value params to send to the server.
+ * @param headers {Object} Keys are header names, values are header values. Multiple
+ * headers of the same name are not supported.
+ */
+var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) {
+ this.fileKey = fileKey || null;
+ this.fileName = fileName || null;
+ this.mimeType = mimeType || null;
+ this.params = params || null;
+ this.headers = headers || null;
+ this.httpMethod = httpMethod || null;
+};
+
+module.exports = FileUploadOptions;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileUploadResult.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileUploadResult.js
new file mode 100644
index 0000000..3110814
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileUploadResult.js
@@ -0,0 +1,31 @@
+cordova.define("cordova-plugin-file.FileUploadResult", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileUploadResult
+ * @constructor
+ */
+module.exports = function FileUploadResult(size, code, content) {
+ this.bytesSent = size;
+ this.responseCode = code;
+ this.response = content;
+ };
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileWriter.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileWriter.js
new file mode 100644
index 0000000..8e3f509
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/FileWriter.js
@@ -0,0 +1,304 @@
+cordova.define("cordova-plugin-file.FileWriter", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec'),
+ FileError = require('./FileError'),
+ ProgressEvent = require('./ProgressEvent');
+
+/**
+ * This class writes to the mobile device file system.
+ *
+ * For Android:
+ * The root directory is the root of the file system.
+ * To write to the SD card, the file name is "sdcard/my_file.txt"
+ *
+ * @constructor
+ * @param file {File} File object containing file properties
+ * @param append if true write to the end of the file, otherwise overwrite the file
+ */
+var FileWriter = function(file) {
+ this.fileName = "";
+ this.length = 0;
+ if (file) {
+ this.localURL = file.localURL || file;
+ this.length = file.size || 0;
+ }
+ // default is to write at the beginning of the file
+ this.position = 0;
+
+ this.readyState = 0; // EMPTY
+
+ this.result = null;
+
+ // Error
+ this.error = null;
+
+ // Event handlers
+ this.onwritestart = null; // When writing starts
+ this.onprogress = null; // While writing the file, and reporting partial file data
+ this.onwrite = null; // When the write has successfully completed.
+ this.onwriteend = null; // When the request has completed (either in success or failure).
+ this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
+ this.onerror = null; // When the write has failed (see errors).
+};
+
+// States
+FileWriter.INIT = 0;
+FileWriter.WRITING = 1;
+FileWriter.DONE = 2;
+
+/**
+ * Abort writing file.
+ */
+FileWriter.prototype.abort = function() {
+ // check for invalid state
+ if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ // set error
+ this.error = new FileError(FileError.ABORT_ERR);
+
+ this.readyState = FileWriter.DONE;
+
+ // If abort callback
+ if (typeof this.onabort === "function") {
+ this.onabort(new ProgressEvent("abort", {"target":this}));
+ }
+
+ // If write end callback
+ if (typeof this.onwriteend === "function") {
+ this.onwriteend(new ProgressEvent("writeend", {"target":this}));
+ }
+};
+
+/**
+ * Writes data to the file
+ *
+ * @param data text or blob to be written
+ */
+FileWriter.prototype.write = function(data) {
+
+ var that=this;
+ var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');
+ var isProxySupportBlobNatively = (cordova.platformId === "windows8" || cordova.platformId === "windows");
+ var isBinary;
+
+ // Check to see if the incoming data is a blob
+ if (data instanceof File || (!isProxySupportBlobNatively && supportsBinary && data instanceof Blob)) {
+ var fileReader = new FileReader();
+ fileReader.onload = function() {
+ // Call this method again, with the arraybuffer as argument
+ FileWriter.prototype.write.call(that, this.result);
+ };
+ if (supportsBinary) {
+ fileReader.readAsArrayBuffer(data);
+ } else {
+ fileReader.readAsText(data);
+ }
+ return;
+ }
+
+ // Mark data type for safer transport over the binary bridge
+ isBinary = supportsBinary && (data instanceof ArrayBuffer);
+ if (isBinary && cordova.platformId === "windowsphone") {
+ // create a plain array, using the keys from the Uint8Array view so that we can serialize it
+ data = Array.apply(null, new Uint8Array(data));
+ }
+
+ // Throw an exception if we are already writing a file
+ if (this.readyState === FileWriter.WRITING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ // WRITING state
+ this.readyState = FileWriter.WRITING;
+
+ var me = this;
+
+ // If onwritestart callback
+ if (typeof me.onwritestart === "function") {
+ me.onwritestart(new ProgressEvent("writestart", {"target":me}));
+ }
+
+ // Write file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // position always increases by bytes written because file would be extended
+ me.position += r;
+ // The length of the file is now where we are done writing.
+
+ me.length = me.position;
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // If onwrite callback
+ if (typeof me.onwrite === "function") {
+ me.onwrite(new ProgressEvent("write", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // Save error
+ me.error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ }, "File", "write", [this.localURL, data, this.position, isBinary]);
+};
+
+/**
+ * Moves the file pointer to the location specified.
+ *
+ * If the offset is a negative number the position of the file
+ * pointer is rewound. If the offset is greater than the file
+ * size the position is set to the end of the file.
+ *
+ * @param offset is the location to move the file pointer to.
+ */
+FileWriter.prototype.seek = function(offset) {
+ // Throw an exception if we are already writing a file
+ if (this.readyState === FileWriter.WRITING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ if (!offset && offset !== 0) {
+ return;
+ }
+
+ // See back from end of file.
+ if (offset < 0) {
+ this.position = Math.max(offset + this.length, 0);
+ }
+ // Offset is bigger than file size so set position
+ // to the end of the file.
+ else if (offset > this.length) {
+ this.position = this.length;
+ }
+ // Offset is between 0 and file size so set the position
+ // to start writing.
+ else {
+ this.position = offset;
+ }
+};
+
+/**
+ * Truncates the file to the size specified.
+ *
+ * @param size to chop the file at.
+ */
+FileWriter.prototype.truncate = function(size) {
+ // Throw an exception if we are already writing a file
+ if (this.readyState === FileWriter.WRITING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ // WRITING state
+ this.readyState = FileWriter.WRITING;
+
+ var me = this;
+
+ // If onwritestart callback
+ if (typeof me.onwritestart === "function") {
+ me.onwritestart(new ProgressEvent("writestart", {"target":this}));
+ }
+
+ // Write file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // Update the length of the file
+ me.length = r;
+ me.position = Math.min(me.position, r);
+
+ // If onwrite callback
+ if (typeof me.onwrite === "function") {
+ me.onwrite(new ProgressEvent("write", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // Save error
+ me.error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ }, "File", "truncate", [this.localURL, size]);
+};
+
+module.exports = FileWriter;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/Flags.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/Flags.js
new file mode 100644
index 0000000..dfac709
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/Flags.js
@@ -0,0 +1,38 @@
+cordova.define("cordova-plugin-file.Flags", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Supplies arguments to methods that lookup or create files and directories.
+ *
+ * @param create
+ * {boolean} file or directory if it doesn't exist
+ * @param exclusive
+ * {boolean} used with create; if true the command will fail if
+ * target path exists
+ */
+function Flags(create, exclusive) {
+ this.create = create || false;
+ this.exclusive = exclusive || false;
+}
+
+module.exports = Flags;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/LocalFileSystem.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/LocalFileSystem.js
new file mode 100644
index 0000000..e424c10
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/LocalFileSystem.js
@@ -0,0 +1,25 @@
+cordova.define("cordova-plugin-file.LocalFileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+exports.TEMPORARY = 0;
+exports.PERSISTENT = 1;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/Metadata.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/Metadata.js
new file mode 100644
index 0000000..efa4b3e
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/Metadata.js
@@ -0,0 +1,42 @@
+cordova.define("cordova-plugin-file.Metadata", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Information about the state of the file or directory
+ *
+ * {Date} modificationTime (readonly)
+ */
+var Metadata = function(metadata) {
+ if (typeof metadata == "object") {
+ this.modificationTime = new Date(metadata.modificationTime);
+ this.size = metadata.size || 0;
+ } else if (typeof metadata == "undefined") {
+ this.modificationTime = null;
+ this.size = 0;
+ } else {
+ /* Backwards compatiblity with platforms that only return a timestamp */
+ this.modificationTime = new Date(metadata);
+ }
+};
+
+module.exports = Metadata;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/ProgressEvent.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/ProgressEvent.js
new file mode 100644
index 0000000..0086f02
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/ProgressEvent.js
@@ -0,0 +1,69 @@
+cordova.define("cordova-plugin-file.ProgressEvent", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+// If ProgressEvent exists in global context, use it already, otherwise use our own polyfill
+// Feature test: See if we can instantiate a native ProgressEvent;
+// if so, use that approach,
+// otherwise fill-in with our own implementation.
+//
+// NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview.
+var ProgressEvent = (function() {
+ /*
+ var createEvent = function(data) {
+ var event = document.createEvent('Events');
+ event.initEvent('ProgressEvent', false, false);
+ if (data) {
+ for (var i in data) {
+ if (data.hasOwnProperty(i)) {
+ event[i] = data[i];
+ }
+ }
+ if (data.target) {
+ // TODO: cannot call .dispatchEvent
+ // need to first figure out how to implement EventTarget
+ }
+ }
+ return event;
+ };
+ try {
+ var ev = createEvent({type:"abort",target:document});
+ return function ProgressEvent(type, data) {
+ data.type = type;
+ return createEvent(data);
+ };
+ } catch(e){
+ */
+ return function ProgressEvent(type, dict) {
+ this.type = type;
+ this.bubbles = false;
+ this.cancelBubble = false;
+ this.cancelable = false;
+ this.lengthComputable = false;
+ this.loaded = dict && dict.loaded ? dict.loaded : 0;
+ this.total = dict && dict.total ? dict.total : 0;
+ this.target = dict && dict.target ? dict.target : null;
+ };
+ //}
+})();
+
+module.exports = ProgressEvent;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/android/FileSystem.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/android/FileSystem.js
new file mode 100644
index 0000000..5da9b9d
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/android/FileSystem.js
@@ -0,0 +1,38 @@
+cordova.define("cordova-plugin-file.androidFileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+FILESYSTEM_PROTOCOL = "cdvfile";
+
+module.exports = {
+ __format__: function(fullPath, nativeUrl) {
+ var path = '/' + this.name + '/' + encodeURI(fullPath);
+ path = path.replace('//','/');
+ var ret = FILESYSTEM_PROTOCOL + '://localhost' + path;
+ var m = /\?.*/.exec(nativeUrl);
+ if (m) {
+ ret += m[0];
+ }
+ return ret;
+ }
+};
+
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystemPaths.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystemPaths.js
new file mode 100644
index 0000000..6e19528
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystemPaths.js
@@ -0,0 +1,65 @@
+cordova.define("cordova-plugin-file.fileSystemPaths", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec');
+var channel = require('cordova/channel');
+
+exports.file = {
+ // Read-only directory where the application is installed.
+ applicationDirectory: null,
+ // Root of app's private writable storage
+ applicationStorageDirectory: null,
+ // Where to put app-specific data files.
+ dataDirectory: null,
+ // Cached files that should survive app restarts.
+ // Apps should not rely on the OS to delete files in here.
+ cacheDirectory: null,
+ // Android: the application space on external storage.
+ externalApplicationStorageDirectory: null,
+ // Android: Where to put app-specific data files on external storage.
+ externalDataDirectory: null,
+ // Android: the application cache on external storage.
+ externalCacheDirectory: null,
+ // Android: the external storage (SD card) root.
+ externalRootDirectory: null,
+ // iOS: Temp directory that the OS can clear at will.
+ tempDirectory: null,
+ // iOS: Holds app-specific files that should be synced (e.g. to iCloud).
+ syncedDataDirectory: null,
+ // iOS: Files private to the app, but that are meaningful to other applciations (e.g. Office files)
+ documentsDirectory: null,
+ // BlackBerry10: Files globally available to all apps
+ sharedDirectory: null
+};
+
+channel.waitForInitialization('onFileSystemPathsReady');
+channel.onCordovaReady.subscribe(function() {
+ function after(paths) {
+ for (var k in paths) {
+ exports.file[k] = paths[k];
+ }
+ channel.initializationComplete('onFileSystemPathsReady');
+ }
+ exec(after, null, 'File', 'requestAllPaths', []);
+});
+
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystems-roots.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystems-roots.js
new file mode 100644
index 0000000..1610b64
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystems-roots.js
@@ -0,0 +1,46 @@
+cordova.define("cordova-plugin-file.fileSystems-roots", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+// Map of fsName -> FileSystem.
+var fsMap = null;
+var FileSystem = require('./FileSystem');
+var exec = require('cordova/exec');
+
+// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.
+require('./fileSystems').getFs = function(name, callback) {
+ if (fsMap) {
+ callback(fsMap[name]);
+ } else {
+ exec(success, null, "File", "requestAllFileSystems", []);
+ function success(response) {
+ fsMap = {};
+ for (var i = 0; i < response.length; ++i) {
+ var fsRoot = response[i];
+ var fs = new FileSystem(fsRoot.filesystemName, fsRoot);
+ fsMap[fs.name] = fs;
+ }
+ callback(fsMap[name]);
+ }
+ }
+};
+
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystems.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystems.js
new file mode 100644
index 0000000..2b8084b
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/fileSystems.js
@@ -0,0 +1,27 @@
+cordova.define("cordova-plugin-file.fileSystems", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.
+module.exports.getFs = function(name, callback) {
+ callback(null);
+};
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/requestFileSystem.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/requestFileSystem.js
new file mode 100644
index 0000000..6626acc
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/requestFileSystem.js
@@ -0,0 +1,78 @@
+cordova.define("cordova-plugin-file.requestFileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+//For browser platform: not all browsers use this file.
+function checkBrowser() {
+ if (cordova.platformId === "browser" && navigator.userAgent.search(/Chrome/) > 0) {
+ var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+ module.exports = requestFileSystem;
+ return;
+ }
+}
+checkBrowser();
+
+var argscheck = require('cordova/argscheck'),
+ FileError = require('./FileError'),
+ FileSystem = require('./FileSystem'),
+ exec = require('cordova/exec');
+var fileSystems = require('./fileSystems');
+
+/**
+ * Request a file system in which to store application data.
+ * @param type local file system type
+ * @param size indicates how much storage space, in bytes, the application expects to need
+ * @param successCallback invoked with a FileSystem object
+ * @param errorCallback invoked if error occurs retrieving file system
+ */
+var requestFileSystem = function(type, size, successCallback, errorCallback) {
+ argscheck.checkArgs('nnFF', 'requestFileSystem', arguments);
+ var fail = function(code) {
+ errorCallback && errorCallback(new FileError(code));
+ };
+
+ if (type < 0) {
+ fail(FileError.SYNTAX_ERR);
+ } else {
+ // if successful, return a FileSystem object
+ var success = function(file_system) {
+ if (file_system) {
+ if (successCallback) {
+ fileSystems.getFs(file_system.name, function(fs) {
+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)
+ if (!fs) {
+ fs = new FileSystem(file_system.name, file_system.root);
+ }
+ successCallback(fs);
+ });
+ }
+ }
+ else {
+ // no FileSystem object returned
+ fail(FileError.NOT_FOUND_ERR);
+ }
+ };
+ exec(success, fail, "File", "requestFileSystem", [type, size]);
+ }
+};
+
+module.exports = requestFileSystem;
+
+});
diff --git a/platforms/android/assets/www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js b/platforms/android/assets/www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js
new file mode 100644
index 0000000..791a005
--- /dev/null
+++ b/platforms/android/assets/www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js
@@ -0,0 +1,89 @@
+cordova.define("cordova-plugin-file.resolveLocalFileSystemURI", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+//For browser platform: not all browsers use overrided `resolveLocalFileSystemURL`.
+function checkBrowser() {
+ if (cordova.platformId === "browser" && navigator.userAgent.search(/Chrome/) > 0) {
+ var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+ module.exports = requestFileSystem;
+ return;
+ }
+}
+checkBrowser();
+
+var argscheck = require('cordova/argscheck'),
+ DirectoryEntry = require('./DirectoryEntry'),
+ FileEntry = require('./FileEntry'),
+ FileError = require('./FileError'),
+ exec = require('cordova/exec');
+var fileSystems = require('./fileSystems');
+
+/**
+ * Look up file system Entry referred to by local URI.
+ * @param {DOMString} uri URI referring to a local file or directory
+ * @param successCallback invoked with Entry object corresponding to URI
+ * @param errorCallback invoked if error occurs retrieving file system entry
+ */
+module.exports.resolveLocalFileSystemURL = function(uri, successCallback, errorCallback) {
+ argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);
+ // error callback
+ var fail = function(error) {
+ errorCallback && errorCallback(new FileError(error));
+ };
+ // sanity check for 'not:valid:filename' or '/not:valid:filename'
+ // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /.
+ if(!uri || uri.split(":").length > 2) {
+ setTimeout( function() {
+ fail(FileError.ENCODING_ERR);
+ },0);
+ return;
+ }
+ // if successful, return either a file or directory entry
+ var success = function(entry) {
+ if (entry) {
+ if (successCallback) {
+ // create appropriate Entry object
+ var fsName = entry.filesystemName || (entry.filesystem && entry.filesystem.name) || (entry.filesystem == window.PERSISTENT ? 'persistent' : 'temporary');
+ fileSystems.getFs(fsName, function(fs) {
+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)
+ if (!fs) {
+ fs = new FileSystem(fsName, {name:"", fullPath:"/"});
+ }
+ var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);
+ successCallback(result);
+ });
+ }
+ }
+ else {
+ // no Entry object returned
+ fail(FileError.NOT_FOUND_ERR);
+ }
+ };
+
+ exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]);
+};
+
+module.exports.resolveLocalFileSystemURI = function() {
+ console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.");
+ module.exports.resolveLocalFileSystemURL.apply(this, arguments);
+};
+
+});
diff --git a/platforms/android/assets/www/templates/tab-dash.html b/platforms/android/assets/www/templates/tab-dash.html
index 58e55ac..f9641b7 100644
--- a/platforms/android/assets/www/templates/tab-dash.html
+++ b/platforms/android/assets/www/templates/tab-dash.html
@@ -40,9 +40,13 @@
Vorschau
-
Jetzt Kaufen
+
Jetzt Kaufen
+
diff --git a/platforms/android/platform_www/cordova_plugins.js b/platforms/android/platform_www/cordova_plugins.js
index d0dae10..e310c63 100644
--- a/platforms/android/platform_www/cordova_plugins.js
+++ b/platforms/android/platform_www/cordova_plugins.js
@@ -55,6 +55,189 @@ module.exports = [
"cordova.InAppBrowser.open",
"window.open"
]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
+ "id": "cordova-plugin-file.DirectoryEntry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.DirectoryEntry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
+ "id": "cordova-plugin-file.DirectoryReader",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.DirectoryReader"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Entry.js",
+ "id": "cordova-plugin-file.Entry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Entry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/File.js",
+ "id": "cordova-plugin-file.File",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.File"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileEntry.js",
+ "id": "cordova-plugin-file.FileEntry",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileEntry"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileError.js",
+ "id": "cordova-plugin-file.FileError",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileError"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileReader.js",
+ "id": "cordova-plugin-file.FileReader",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileReader"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileSystem.js",
+ "id": "cordova-plugin-file.FileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
+ "id": "cordova-plugin-file.FileUploadOptions",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileUploadOptions"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
+ "id": "cordova-plugin-file.FileUploadResult",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileUploadResult"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/FileWriter.js",
+ "id": "cordova-plugin-file.FileWriter",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.FileWriter"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Flags.js",
+ "id": "cordova-plugin-file.Flags",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Flags"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
+ "id": "cordova-plugin-file.LocalFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.LocalFileSystem"
+ ],
+ "merges": [
+ "window"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/Metadata.js",
+ "id": "cordova-plugin-file.Metadata",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.Metadata"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
+ "id": "cordova-plugin-file.ProgressEvent",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.ProgressEvent"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystems.js",
+ "id": "cordova-plugin-file.fileSystems",
+ "pluginId": "cordova-plugin-file"
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
+ "id": "cordova-plugin-file.requestFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "clobbers": [
+ "window.requestFileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
+ "id": "cordova-plugin-file.resolveLocalFileSystemURI",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "window"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/android/FileSystem.js",
+ "id": "cordova-plugin-file.androidFileSystem",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "FileSystem"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
+ "id": "cordova-plugin-file.fileSystems-roots",
+ "pluginId": "cordova-plugin-file",
+ "runs": true
+ },
+ {
+ "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
+ "id": "cordova-plugin-file.fileSystemPaths",
+ "pluginId": "cordova-plugin-file",
+ "merges": [
+ "cordova"
+ ],
+ "runs": true
+ },
+ {
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
+ "id": "cordova-plugin-file-transfer.FileTransferError",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransferError"
+ ]
+ },
+ {
+ "file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
+ "id": "cordova-plugin-file-transfer.FileTransfer",
+ "pluginId": "cordova-plugin-file-transfer",
+ "clobbers": [
+ "window.FileTransfer"
+ ]
}
];
module.exports.metadata =
@@ -67,7 +250,9 @@ module.exports.metadata =
"cordova-plugin-statusbar": "2.0.0",
"cordova-plugin-whitelist": "1.2.0",
"ionic-plugin-keyboard": "1.0.8",
- "cordova-plugin-inappbrowser": "1.1.1"
+ "cordova-plugin-inappbrowser": "1.1.1",
+ "cordova-plugin-file": "3.0.0",
+ "cordova-plugin-file-transfer": "1.4.0"
}
// BOTTOM OF METADATA
});
\ No newline at end of file
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file-transfer/www/FileTransfer.js b/platforms/android/platform_www/plugins/cordova-plugin-file-transfer/www/FileTransfer.js
new file mode 100644
index 0000000..ff0e6c9
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file-transfer/www/FileTransfer.js
@@ -0,0 +1,237 @@
+cordova.define("cordova-plugin-file-transfer.FileTransfer", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ FileTransferError = require('./FileTransferError'),
+ ProgressEvent = require('cordova-plugin-file.ProgressEvent');
+
+function newProgressEvent(result) {
+ var pe = new ProgressEvent();
+ pe.lengthComputable = result.lengthComputable;
+ pe.loaded = result.loaded;
+ pe.total = result.total;
+ return pe;
+}
+
+function getUrlCredentials(urlString) {
+ var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
+ credentials = credentialsPattern.exec(urlString);
+
+ return credentials && credentials[1];
+}
+
+function getBasicAuthHeader(urlString) {
+ var header = null;
+
+
+ // This is changed due to MS Windows doesn't support credentials in http uris
+ // so we detect them by regexp and strip off from result url
+ // Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem
+
+ if (window.btoa) {
+ var credentials = getUrlCredentials(urlString);
+ if (credentials) {
+ var authHeader = "Authorization";
+ var authHeaderValue = "Basic " + window.btoa(credentials);
+
+ header = {
+ name : authHeader,
+ value : authHeaderValue
+ };
+ }
+ }
+
+ 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;
+
+/**
+ * FileTransfer uploads a file to a remote server.
+ * @constructor
+ */
+var FileTransfer = function() {
+ this._id = ++idCounter;
+ this.onprogress = null; // optional callback
+};
+
+/**
+* Given an absolute file path, uploads a file on the device to a remote server
+* using a multipart HTTP request.
+* @param filePath {String} Full path of the file on the device
+* @param server {String} URL of the server to receive the file
+* @param successCallback (Function} Callback to be invoked when upload has completed
+* @param errorCallback {Function} Callback to be invoked upon error
+* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
+* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+*/
+FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
+ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
+ // check for options
+ var fileKey = null;
+ var fileName = null;
+ var mimeType = null;
+ var params = null;
+ var chunkedMode = true;
+ var headers = null;
+ var httpMethod = null;
+ var basicAuthHeader = getBasicAuthHeader(server);
+ if (basicAuthHeader) {
+ server = server.replace(getUrlCredentials(server) + '@', '');
+
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ if (options) {
+ fileKey = options.fileKey;
+ fileName = options.fileName;
+ mimeType = options.mimeType;
+ headers = options.headers;
+ httpMethod = options.httpMethod || "POST";
+ if (httpMethod.toUpperCase() == "PUT"){
+ httpMethod = "PUT";
+ } else {
+ httpMethod = "POST";
+ }
+ if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
+ chunkedMode = options.chunkedMode;
+ }
+ if (options.params) {
+ params = options.params;
+ }
+ else {
+ params = {};
+ }
+ }
+
+ 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);
+ };
+
+ var self = this;
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ self.onprogress(newProgressEvent(result));
+ }
+ } else {
+ successCallback && successCallback(result);
+ }
+ };
+ exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+};
+
+/**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ * @param source {String} URL of the server to receive the file
+ * @param target {String} Full path of the file on the device
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ * @param options {FileDownloadOptions} Optional parameters such as headers
+ */
+FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
+ argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
+ var self = this;
+
+ var basicAuthHeader = getBasicAuthHeader(source);
+ if (basicAuthHeader) {
+ source = source.replace(getUrlCredentials(source) + '@', '');
+
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var headers = null;
+ if (options) {
+ headers = options.headers || null;
+ }
+
+ if (cordova.platformId === "windowsphone" && headers) {
+ headers = convertHeadersToArray(headers);
+ }
+
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ return self.onprogress(newProgressEvent(result));
+ }
+ } else if (successCallback) {
+ var entry = null;
+ if (result.isDirectory) {
+ entry = new (require('cordova-plugin-file.DirectoryEntry'))();
+ }
+ else if (result.isFile) {
+ entry = new (require('cordova-plugin-file.FileEntry'))();
+ }
+ entry.isDirectory = result.isDirectory;
+ entry.isFile = result.isFile;
+ entry.name = result.name;
+ entry.fullPath = result.fullPath;
+ entry.filesystem = new FileSystem(result.filesystemName || (result.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
+ entry.nativeURL = result.nativeURL;
+ successCallback(entry);
+ }
+ };
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
+ errorCallback(error);
+ };
+
+ exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);
+};
+
+/**
+ * Aborts the ongoing file transfer on this object. The original error
+ * callback for the file transfer will be called if necessary.
+ */
+FileTransfer.prototype.abort = function() {
+ exec(null, null, 'FileTransfer', 'abort', [this._id]);
+};
+
+module.exports = FileTransfer;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file-transfer/www/FileTransferError.js b/platforms/android/platform_www/plugins/cordova-plugin-file-transfer/www/FileTransferError.js
new file mode 100644
index 0000000..8339c2b
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file-transfer/www/FileTransferError.js
@@ -0,0 +1,43 @@
+cordova.define("cordova-plugin-file-transfer.FileTransferError", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileTransferError
+ * @constructor
+ */
+var FileTransferError = function(code, source, target, status, body, exception) {
+ this.code = code || null;
+ this.source = source || null;
+ this.target = target || null;
+ this.http_status = status || null;
+ this.body = body || null;
+ this.exception = exception || null;
+};
+
+FileTransferError.FILE_NOT_FOUND_ERR = 1;
+FileTransferError.INVALID_URL_ERR = 2;
+FileTransferError.CONNECTION_ERR = 3;
+FileTransferError.ABORT_ERR = 4;
+FileTransferError.NOT_MODIFIED_ERR = 5;
+
+module.exports = FileTransferError;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/DirectoryEntry.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/DirectoryEntry.js
new file mode 100644
index 0000000..464d339
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/DirectoryEntry.js
@@ -0,0 +1,119 @@
+cordova.define("cordova-plugin-file.DirectoryEntry", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var argscheck = require('cordova/argscheck'),
+ utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ Entry = require('./Entry'),
+ FileError = require('./FileError'),
+ DirectoryReader = require('./DirectoryReader');
+
+/**
+ * An interface representing a directory on the file system.
+ *
+ * {boolean} isFile always false (readonly)
+ * {boolean} isDirectory always true (readonly)
+ * {DOMString} name of the directory, excluding the path leading to it (readonly)
+ * {DOMString} fullPath the absolute full path to the directory (readonly)
+ * {FileSystem} filesystem on which the directory resides (readonly)
+ */
+var DirectoryEntry = function(name, fullPath, fileSystem, nativeURL) {
+
+ // add trailing slash if it is missing
+ if ((fullPath) && !/\/$/.test(fullPath)) {
+ fullPath += "/";
+ }
+ // add trailing slash if it is missing
+ if (nativeURL && !/\/$/.test(nativeURL)) {
+ nativeURL += "/";
+ }
+ DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);
+};
+
+utils.extend(DirectoryEntry, Entry);
+
+/**
+ * Creates a new DirectoryReader to read entries from this directory
+ */
+DirectoryEntry.prototype.createReader = function() {
+ return new DirectoryReader(this.toInternalURL());
+};
+
+/**
+ * Creates or looks up a directory
+ *
+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
+ * @param {Flags} options to create or exclusively create the directory
+ * @param {Function} successCallback is called with the new entry
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
+ var fs = this.filesystem;
+ var win = successCallback && function(result) {
+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getDirectory", [this.toInternalURL(), path, options]);
+};
+
+/**
+ * Deletes a directory and all of it's contents
+ *
+ * @param {Function} successCallback is called with no parameters
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(successCallback, fail, "File", "removeRecursively", [this.toInternalURL()]);
+};
+
+/**
+ * Creates or looks up a file
+ *
+ * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
+ * @param {Flags} options to create or exclusively create the file
+ * @param {Function} successCallback is called with the new entry
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) {
+ argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
+ var fs = this.filesystem;
+ var win = successCallback && function(result) {
+ var FileEntry = require('./FileEntry');
+ var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getFile", [this.toInternalURL(), path, options]);
+};
+
+module.exports = DirectoryEntry;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/DirectoryReader.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/DirectoryReader.js
new file mode 100644
index 0000000..921b486
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/DirectoryReader.js
@@ -0,0 +1,75 @@
+cordova.define("cordova-plugin-file.DirectoryReader", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec'),
+ FileError = require('./FileError') ;
+
+/**
+ * An interface that lists the files and directories in a directory.
+ */
+function DirectoryReader(localURL) {
+ this.localURL = localURL || null;
+ this.hasReadEntries = false;
+}
+
+/**
+ * Returns a list of entries from a directory.
+ *
+ * @param {Function} successCallback is called with a list of entries
+ * @param {Function} errorCallback is called with a FileError
+ */
+DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
+ // If we've already read and passed on this directory's entries, return an empty list.
+ if (this.hasReadEntries) {
+ successCallback([]);
+ return;
+ }
+ var reader = this;
+ var win = typeof successCallback !== 'function' ? null : function(result) {
+ var retVal = [];
+ for (var i=0; i or
+ * tag. If that is not possible, construct a cdvfile:// URL.
+ */
+Entry.prototype.toURL = function() {
+ if (this.nativeURL) {
+ return this.nativeURL;
+ }
+ // fullPath attribute may contain the full URL in the case that
+ // toInternalURL fails.
+ return this.toInternalURL() || "file://localhost" + this.fullPath;
+};
+
+/**
+ * Backwards-compatibility: In v1.0.0 - 1.0.2, .toURL would only return a
+ * cdvfile:// URL, and this method was necessary to obtain URLs usable by the
+ * webview.
+ * See CB-6051, CB-6106, CB-6117, CB-6152, CB-6199, CB-6201, CB-6243, CB-6249,
+ * and CB-6300.
+ */
+Entry.prototype.toNativeURL = function() {
+ console.log("DEPRECATED: Update your code to use 'toURL'");
+ return this.toURL();
+};
+
+/**
+ * Returns a URI that can be used to identify this entry.
+ *
+ * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
+ * @return uri
+ */
+Entry.prototype.toURI = function(mimeType) {
+ console.log("DEPRECATED: Update your code to use 'toURL'");
+ return this.toURL();
+};
+
+/**
+ * Remove a file or directory. It is an error to attempt to delete a
+ * directory that is not empty. It is an error to attempt to delete a
+ * root directory of a file system.
+ *
+ * @param successCallback {Function} called with no parameters
+ * @param errorCallback {Function} called with a FileError
+ */
+Entry.prototype.remove = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.remove', arguments);
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(successCallback, fail, "File", "remove", [this.toInternalURL()]);
+};
+
+/**
+ * Look up the parent DirectoryEntry of this entry.
+ *
+ * @param successCallback {Function} called with the parent DirectoryEntry object
+ * @param errorCallback {Function} called with a FileError
+ */
+Entry.prototype.getParent = function(successCallback, errorCallback) {
+ argscheck.checkArgs('FF', 'Entry.getParent', arguments);
+ var fs = this.filesystem;
+ var win = successCallback && function(result) {
+ var DirectoryEntry = require('./DirectoryEntry');
+ var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
+ successCallback(entry);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getParent", [this.toInternalURL()]);
+};
+
+module.exports = Entry;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/File.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/File.js
new file mode 100644
index 0000000..47c267b
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/File.js
@@ -0,0 +1,81 @@
+cordova.define("cordova-plugin-file.File", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Constructor.
+ * name {DOMString} name of the file, without path information
+ * fullPath {DOMString} the full path of the file, including the name
+ * type {DOMString} mime type
+ * lastModifiedDate {Date} last modified date
+ * size {Number} size of the file in bytes
+ */
+
+var File = function(name, localURL, type, lastModifiedDate, size){
+ this.name = name || '';
+ this.localURL = localURL || null;
+ this.type = type || null;
+ this.lastModified = lastModifiedDate || null;
+ // For backwards compatibility, store the timestamp in lastModifiedDate as well
+ this.lastModifiedDate = lastModifiedDate || null;
+ this.size = size || 0;
+
+ // These store the absolute start and end for slicing the file.
+ this.start = 0;
+ this.end = this.size;
+};
+
+/**
+ * Returns a "slice" of the file. Since Cordova Files don't contain the actual
+ * content, this really returns a File with adjusted start and end.
+ * Slices of slices are supported.
+ * start {Number} The index at which to start the slice (inclusive).
+ * end {Number} The index at which to end the slice (exclusive).
+ */
+File.prototype.slice = function(start, end) {
+ var size = this.end - this.start;
+ var newStart = 0;
+ var newEnd = size;
+ if (arguments.length) {
+ if (start < 0) {
+ newStart = Math.max(size + start, 0);
+ } else {
+ newStart = Math.min(size, start);
+ }
+ }
+
+ if (arguments.length >= 2) {
+ if (end < 0) {
+ newEnd = Math.max(size + end, 0);
+ } else {
+ newEnd = Math.min(end, size);
+ }
+ }
+
+ var newFile = new File(this.name, this.localURL, this.type, this.lastModified, this.size);
+ newFile.start = this.start + newStart;
+ newFile.end = this.start + newEnd;
+ return newFile;
+};
+
+
+module.exports = File;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileEntry.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileEntry.js
new file mode 100644
index 0000000..981ae7b
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileEntry.js
@@ -0,0 +1,83 @@
+cordova.define("cordova-plugin-file.FileEntry", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var utils = require('cordova/utils'),
+ exec = require('cordova/exec'),
+ Entry = require('./Entry'),
+ FileWriter = require('./FileWriter'),
+ File = require('./File'),
+ FileError = require('./FileError');
+
+/**
+ * An interface representing a file on the file system.
+ *
+ * {boolean} isFile always true (readonly)
+ * {boolean} isDirectory always false (readonly)
+ * {DOMString} name of the file, excluding the path leading to it (readonly)
+ * {DOMString} fullPath the absolute full path to the file (readonly)
+ * {FileSystem} filesystem on which the file resides (readonly)
+ */
+var FileEntry = function(name, fullPath, fileSystem, nativeURL) {
+ FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);
+};
+
+utils.extend(FileEntry, Entry);
+
+/**
+ * Creates a new FileWriter associated with the file that this FileEntry represents.
+ *
+ * @param {Function} successCallback is called with the new FileWriter
+ * @param {Function} errorCallback is called with a FileError
+ */
+FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
+ this.file(function(filePointer) {
+ var writer = new FileWriter(filePointer);
+
+ if (writer.localURL === null || writer.localURL === "") {
+ errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR));
+ } else {
+ successCallback && successCallback(writer);
+ }
+ }, errorCallback);
+};
+
+/**
+ * Returns a File that represents the current state of the file that this FileEntry represents.
+ *
+ * @param {Function} successCallback is called with the new File object
+ * @param {Function} errorCallback is called with a FileError
+ */
+FileEntry.prototype.file = function(successCallback, errorCallback) {
+ var localURL = this.toInternalURL();
+ var win = successCallback && function(f) {
+ var file = new File(f.name, localURL, f.type, f.lastModifiedDate, f.size);
+ successCallback(file);
+ };
+ var fail = errorCallback && function(code) {
+ errorCallback(new FileError(code));
+ };
+ exec(win, fail, "File", "getFileMetadata", [localURL]);
+};
+
+
+module.exports = FileEntry;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileError.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileError.js
new file mode 100644
index 0000000..403f73b
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileError.js
@@ -0,0 +1,48 @@
+cordova.define("cordova-plugin-file.FileError", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileError
+ */
+function FileError(error) {
+ this.code = error || null;
+}
+
+// File error codes
+// Found in DOMException
+FileError.NOT_FOUND_ERR = 1;
+FileError.SECURITY_ERR = 2;
+FileError.ABORT_ERR = 3;
+
+// Added by File API specification
+FileError.NOT_READABLE_ERR = 4;
+FileError.ENCODING_ERR = 5;
+FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
+FileError.INVALID_STATE_ERR = 7;
+FileError.SYNTAX_ERR = 8;
+FileError.INVALID_MODIFICATION_ERR = 9;
+FileError.QUOTA_EXCEEDED_ERR = 10;
+FileError.TYPE_MISMATCH_ERR = 11;
+FileError.PATH_EXISTS_ERR = 12;
+
+module.exports = FileError;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileReader.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileReader.js
new file mode 100644
index 0000000..6955e9f
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileReader.js
@@ -0,0 +1,392 @@
+cordova.define("cordova-plugin-file.FileReader", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec'),
+ modulemapper = require('cordova/modulemapper'),
+ utils = require('cordova/utils'),
+ File = require('./File'),
+ FileError = require('./FileError'),
+ ProgressEvent = require('./ProgressEvent'),
+ origFileReader = modulemapper.getOriginalSymbol(window, 'FileReader');
+
+/**
+ * This class reads the mobile device file system.
+ *
+ * For Android:
+ * The root directory is the root of the file system.
+ * To read from the SD card, the file name is "sdcard/my_file.txt"
+ * @constructor
+ */
+var FileReader = function() {
+ this._readyState = 0;
+ this._error = null;
+ this._result = null;
+ this._localURL = '';
+ this._realReader = origFileReader ? new origFileReader() : {};
+};
+
+// States
+FileReader.EMPTY = 0;
+FileReader.LOADING = 1;
+FileReader.DONE = 2;
+
+utils.defineGetter(FileReader.prototype, 'readyState', function() {
+ return this._localURL ? this._readyState : this._realReader.readyState;
+});
+
+utils.defineGetter(FileReader.prototype, 'error', function() {
+ return this._localURL ? this._error: this._realReader.error;
+});
+
+utils.defineGetter(FileReader.prototype, 'result', function() {
+ return this._localURL ? this._result: this._realReader.result;
+});
+
+function defineEvent(eventName) {
+ utils.defineGetterSetter(FileReader.prototype, eventName, function() {
+ return this._realReader[eventName] || null;
+ }, function(value) {
+ this._realReader[eventName] = value;
+ });
+}
+defineEvent('onloadstart'); // When the read starts.
+defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)
+defineEvent('onload'); // When the read has successfully completed.
+defineEvent('onerror'); // When the read has failed (see errors).
+defineEvent('onloadend'); // When the request has completed (either in success or failure).
+defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.
+
+function initRead(reader, file) {
+ // Already loading something
+ if (reader.readyState == FileReader.LOADING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ reader._result = null;
+ reader._error = null;
+ reader._readyState = FileReader.LOADING;
+
+ if (typeof file.localURL == 'string') {
+ reader._localURL = file.localURL;
+ } else {
+ reader._localURL = '';
+ return true;
+ }
+
+ reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader}));
+}
+
+/**
+ * Abort reading file.
+ */
+FileReader.prototype.abort = function() {
+ if (origFileReader && !this._localURL) {
+ return this._realReader.abort();
+ }
+ this._result = null;
+
+ if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) {
+ return;
+ }
+
+ this._readyState = FileReader.DONE;
+
+ // If abort callback
+ if (typeof this.onabort === 'function') {
+ this.onabort(new ProgressEvent('abort', {target:this}));
+ }
+ // If load end callback
+ if (typeof this.onloadend === 'function') {
+ this.onloadend(new ProgressEvent('loadend', {target:this}));
+ }
+};
+
+/**
+ * Read text file.
+ *
+ * @param file {File} File object containing file properties
+ * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
+ */
+FileReader.prototype.readAsText = function(file, encoding) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsText(file, encoding);
+ }
+
+ // Default encoding is UTF-8
+ var enc = encoding ? encoding : "UTF-8";
+ var me = this;
+ var execArgs = [this._localURL, enc, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // Save result
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // null result
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsText", execArgs);
+};
+
+
+/**
+ * Read file and return data as a base64 encoded data url.
+ * A data url is of the form:
+ * data:[][;base64],
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsDataURL = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsDataURL(file);
+ }
+
+ var me = this;
+ var execArgs = [this._localURL, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ // Save result
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsDataURL", execArgs);
+};
+
+/**
+ * Read file and return data as a binary data.
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsBinaryString = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsBinaryString(file);
+ }
+
+ var me = this;
+ var execArgs = [this._localURL, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsBinaryString", execArgs);
+};
+
+/**
+ * Read file and return data as a binary data.
+ *
+ * @param file {File} File object containing file properties
+ */
+FileReader.prototype.readAsArrayBuffer = function(file) {
+ if (initRead(this, file)) {
+ return this._realReader.readAsArrayBuffer(file);
+ }
+
+ var me = this;
+ var execArgs = [this._localURL, file.start, file.end];
+
+ // Read file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ if (r instanceof Array) {
+ r = new Uint8Array(r).buffer;
+ }
+ me._result = r;
+
+ // If onload callback
+ if (typeof me.onload === "function") {
+ me.onload(new ProgressEvent("load", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me._readyState === FileReader.DONE) {
+ return;
+ }
+
+ // DONE state
+ me._readyState = FileReader.DONE;
+
+ me._result = null;
+
+ // Save error
+ me._error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {target:me}));
+ }
+
+ // If onloadend callback
+ if (typeof me.onloadend === "function") {
+ me.onloadend(new ProgressEvent("loadend", {target:me}));
+ }
+ }, "File", "readAsArrayBuffer", execArgs);
+};
+
+module.exports = FileReader;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileSystem.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileSystem.js
new file mode 100644
index 0000000..26639b1
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileSystem.js
@@ -0,0 +1,50 @@
+cordova.define("cordova-plugin-file.FileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var DirectoryEntry = require('./DirectoryEntry');
+
+/**
+ * An interface representing a file system
+ *
+ * @constructor
+ * {DOMString} name the unique name of the file system (readonly)
+ * {DirectoryEntry} root directory of the file system (readonly)
+ */
+var FileSystem = function(name, root) {
+ this.name = name;
+ if (root) {
+ this.root = new DirectoryEntry(root.name, root.fullPath, this, root.nativeURL);
+ } else {
+ this.root = new DirectoryEntry(this.name, '/', this);
+ }
+};
+
+FileSystem.prototype.__format__ = function(fullPath, nativeUrl) {
+ return fullPath;
+};
+
+FileSystem.prototype.toJSON = function() {
+ return "";
+};
+
+module.exports = FileSystem;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileUploadOptions.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileUploadOptions.js
new file mode 100644
index 0000000..9928359
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileUploadOptions.js
@@ -0,0 +1,43 @@
+cordova.define("cordova-plugin-file.FileUploadOptions", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Options to customize the HTTP request used to upload files.
+ * @constructor
+ * @param fileKey {String} Name of file request parameter.
+ * @param fileName {String} Filename to be used by the server. Defaults to image.jpg.
+ * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.
+ * @param params {Object} Object with key: value params to send to the server.
+ * @param headers {Object} Keys are header names, values are header values. Multiple
+ * headers of the same name are not supported.
+ */
+var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) {
+ this.fileKey = fileKey || null;
+ this.fileName = fileName || null;
+ this.mimeType = mimeType || null;
+ this.params = params || null;
+ this.headers = headers || null;
+ this.httpMethod = httpMethod || null;
+};
+
+module.exports = FileUploadOptions;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileUploadResult.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileUploadResult.js
new file mode 100644
index 0000000..3110814
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileUploadResult.js
@@ -0,0 +1,31 @@
+cordova.define("cordova-plugin-file.FileUploadResult", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileUploadResult
+ * @constructor
+ */
+module.exports = function FileUploadResult(size, code, content) {
+ this.bytesSent = size;
+ this.responseCode = code;
+ this.response = content;
+ };
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.js
new file mode 100644
index 0000000..8e3f509
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.js
@@ -0,0 +1,304 @@
+cordova.define("cordova-plugin-file.FileWriter", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec'),
+ FileError = require('./FileError'),
+ ProgressEvent = require('./ProgressEvent');
+
+/**
+ * This class writes to the mobile device file system.
+ *
+ * For Android:
+ * The root directory is the root of the file system.
+ * To write to the SD card, the file name is "sdcard/my_file.txt"
+ *
+ * @constructor
+ * @param file {File} File object containing file properties
+ * @param append if true write to the end of the file, otherwise overwrite the file
+ */
+var FileWriter = function(file) {
+ this.fileName = "";
+ this.length = 0;
+ if (file) {
+ this.localURL = file.localURL || file;
+ this.length = file.size || 0;
+ }
+ // default is to write at the beginning of the file
+ this.position = 0;
+
+ this.readyState = 0; // EMPTY
+
+ this.result = null;
+
+ // Error
+ this.error = null;
+
+ // Event handlers
+ this.onwritestart = null; // When writing starts
+ this.onprogress = null; // While writing the file, and reporting partial file data
+ this.onwrite = null; // When the write has successfully completed.
+ this.onwriteend = null; // When the request has completed (either in success or failure).
+ this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
+ this.onerror = null; // When the write has failed (see errors).
+};
+
+// States
+FileWriter.INIT = 0;
+FileWriter.WRITING = 1;
+FileWriter.DONE = 2;
+
+/**
+ * Abort writing file.
+ */
+FileWriter.prototype.abort = function() {
+ // check for invalid state
+ if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ // set error
+ this.error = new FileError(FileError.ABORT_ERR);
+
+ this.readyState = FileWriter.DONE;
+
+ // If abort callback
+ if (typeof this.onabort === "function") {
+ this.onabort(new ProgressEvent("abort", {"target":this}));
+ }
+
+ // If write end callback
+ if (typeof this.onwriteend === "function") {
+ this.onwriteend(new ProgressEvent("writeend", {"target":this}));
+ }
+};
+
+/**
+ * Writes data to the file
+ *
+ * @param data text or blob to be written
+ */
+FileWriter.prototype.write = function(data) {
+
+ var that=this;
+ var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');
+ var isProxySupportBlobNatively = (cordova.platformId === "windows8" || cordova.platformId === "windows");
+ var isBinary;
+
+ // Check to see if the incoming data is a blob
+ if (data instanceof File || (!isProxySupportBlobNatively && supportsBinary && data instanceof Blob)) {
+ var fileReader = new FileReader();
+ fileReader.onload = function() {
+ // Call this method again, with the arraybuffer as argument
+ FileWriter.prototype.write.call(that, this.result);
+ };
+ if (supportsBinary) {
+ fileReader.readAsArrayBuffer(data);
+ } else {
+ fileReader.readAsText(data);
+ }
+ return;
+ }
+
+ // Mark data type for safer transport over the binary bridge
+ isBinary = supportsBinary && (data instanceof ArrayBuffer);
+ if (isBinary && cordova.platformId === "windowsphone") {
+ // create a plain array, using the keys from the Uint8Array view so that we can serialize it
+ data = Array.apply(null, new Uint8Array(data));
+ }
+
+ // Throw an exception if we are already writing a file
+ if (this.readyState === FileWriter.WRITING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ // WRITING state
+ this.readyState = FileWriter.WRITING;
+
+ var me = this;
+
+ // If onwritestart callback
+ if (typeof me.onwritestart === "function") {
+ me.onwritestart(new ProgressEvent("writestart", {"target":me}));
+ }
+
+ // Write file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // position always increases by bytes written because file would be extended
+ me.position += r;
+ // The length of the file is now where we are done writing.
+
+ me.length = me.position;
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // If onwrite callback
+ if (typeof me.onwrite === "function") {
+ me.onwrite(new ProgressEvent("write", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // Save error
+ me.error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ }, "File", "write", [this.localURL, data, this.position, isBinary]);
+};
+
+/**
+ * Moves the file pointer to the location specified.
+ *
+ * If the offset is a negative number the position of the file
+ * pointer is rewound. If the offset is greater than the file
+ * size the position is set to the end of the file.
+ *
+ * @param offset is the location to move the file pointer to.
+ */
+FileWriter.prototype.seek = function(offset) {
+ // Throw an exception if we are already writing a file
+ if (this.readyState === FileWriter.WRITING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ if (!offset && offset !== 0) {
+ return;
+ }
+
+ // See back from end of file.
+ if (offset < 0) {
+ this.position = Math.max(offset + this.length, 0);
+ }
+ // Offset is bigger than file size so set position
+ // to the end of the file.
+ else if (offset > this.length) {
+ this.position = this.length;
+ }
+ // Offset is between 0 and file size so set the position
+ // to start writing.
+ else {
+ this.position = offset;
+ }
+};
+
+/**
+ * Truncates the file to the size specified.
+ *
+ * @param size to chop the file at.
+ */
+FileWriter.prototype.truncate = function(size) {
+ // Throw an exception if we are already writing a file
+ if (this.readyState === FileWriter.WRITING) {
+ throw new FileError(FileError.INVALID_STATE_ERR);
+ }
+
+ // WRITING state
+ this.readyState = FileWriter.WRITING;
+
+ var me = this;
+
+ // If onwritestart callback
+ if (typeof me.onwritestart === "function") {
+ me.onwritestart(new ProgressEvent("writestart", {"target":this}));
+ }
+
+ // Write file
+ exec(
+ // Success callback
+ function(r) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // Update the length of the file
+ me.length = r;
+ me.position = Math.min(me.position, r);
+
+ // If onwrite callback
+ if (typeof me.onwrite === "function") {
+ me.onwrite(new ProgressEvent("write", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ },
+ // Error callback
+ function(e) {
+ // If DONE (cancelled), then don't do anything
+ if (me.readyState === FileWriter.DONE) {
+ return;
+ }
+
+ // DONE state
+ me.readyState = FileWriter.DONE;
+
+ // Save error
+ me.error = new FileError(e);
+
+ // If onerror callback
+ if (typeof me.onerror === "function") {
+ me.onerror(new ProgressEvent("error", {"target":me}));
+ }
+
+ // If onwriteend callback
+ if (typeof me.onwriteend === "function") {
+ me.onwriteend(new ProgressEvent("writeend", {"target":me}));
+ }
+ }, "File", "truncate", [this.localURL, size]);
+};
+
+module.exports = FileWriter;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/Flags.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/Flags.js
new file mode 100644
index 0000000..dfac709
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/Flags.js
@@ -0,0 +1,38 @@
+cordova.define("cordova-plugin-file.Flags", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Supplies arguments to methods that lookup or create files and directories.
+ *
+ * @param create
+ * {boolean} file or directory if it doesn't exist
+ * @param exclusive
+ * {boolean} used with create; if true the command will fail if
+ * target path exists
+ */
+function Flags(create, exclusive) {
+ this.create = create || false;
+ this.exclusive = exclusive || false;
+}
+
+module.exports = Flags;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/LocalFileSystem.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/LocalFileSystem.js
new file mode 100644
index 0000000..e424c10
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/LocalFileSystem.js
@@ -0,0 +1,25 @@
+cordova.define("cordova-plugin-file.LocalFileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+exports.TEMPORARY = 0;
+exports.PERSISTENT = 1;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/Metadata.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/Metadata.js
new file mode 100644
index 0000000..efa4b3e
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/Metadata.js
@@ -0,0 +1,42 @@
+cordova.define("cordova-plugin-file.Metadata", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * Information about the state of the file or directory
+ *
+ * {Date} modificationTime (readonly)
+ */
+var Metadata = function(metadata) {
+ if (typeof metadata == "object") {
+ this.modificationTime = new Date(metadata.modificationTime);
+ this.size = metadata.size || 0;
+ } else if (typeof metadata == "undefined") {
+ this.modificationTime = null;
+ this.size = 0;
+ } else {
+ /* Backwards compatiblity with platforms that only return a timestamp */
+ this.modificationTime = new Date(metadata);
+ }
+};
+
+module.exports = Metadata;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/ProgressEvent.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/ProgressEvent.js
new file mode 100644
index 0000000..0086f02
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/ProgressEvent.js
@@ -0,0 +1,69 @@
+cordova.define("cordova-plugin-file.ProgressEvent", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+// If ProgressEvent exists in global context, use it already, otherwise use our own polyfill
+// Feature test: See if we can instantiate a native ProgressEvent;
+// if so, use that approach,
+// otherwise fill-in with our own implementation.
+//
+// NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview.
+var ProgressEvent = (function() {
+ /*
+ var createEvent = function(data) {
+ var event = document.createEvent('Events');
+ event.initEvent('ProgressEvent', false, false);
+ if (data) {
+ for (var i in data) {
+ if (data.hasOwnProperty(i)) {
+ event[i] = data[i];
+ }
+ }
+ if (data.target) {
+ // TODO: cannot call .dispatchEvent
+ // need to first figure out how to implement EventTarget
+ }
+ }
+ return event;
+ };
+ try {
+ var ev = createEvent({type:"abort",target:document});
+ return function ProgressEvent(type, data) {
+ data.type = type;
+ return createEvent(data);
+ };
+ } catch(e){
+ */
+ return function ProgressEvent(type, dict) {
+ this.type = type;
+ this.bubbles = false;
+ this.cancelBubble = false;
+ this.cancelable = false;
+ this.lengthComputable = false;
+ this.loaded = dict && dict.loaded ? dict.loaded : 0;
+ this.total = dict && dict.total ? dict.total : 0;
+ this.target = dict && dict.target ? dict.target : null;
+ };
+ //}
+})();
+
+module.exports = ProgressEvent;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/android/FileSystem.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/android/FileSystem.js
new file mode 100644
index 0000000..5da9b9d
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/android/FileSystem.js
@@ -0,0 +1,38 @@
+cordova.define("cordova-plugin-file.androidFileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+FILESYSTEM_PROTOCOL = "cdvfile";
+
+module.exports = {
+ __format__: function(fullPath, nativeUrl) {
+ var path = '/' + this.name + '/' + encodeURI(fullPath);
+ path = path.replace('//','/');
+ var ret = FILESYSTEM_PROTOCOL + '://localhost' + path;
+ var m = /\?.*/.exec(nativeUrl);
+ if (m) {
+ ret += m[0];
+ }
+ return ret;
+ }
+};
+
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystemPaths.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystemPaths.js
new file mode 100644
index 0000000..6e19528
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystemPaths.js
@@ -0,0 +1,65 @@
+cordova.define("cordova-plugin-file.fileSystemPaths", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+var exec = require('cordova/exec');
+var channel = require('cordova/channel');
+
+exports.file = {
+ // Read-only directory where the application is installed.
+ applicationDirectory: null,
+ // Root of app's private writable storage
+ applicationStorageDirectory: null,
+ // Where to put app-specific data files.
+ dataDirectory: null,
+ // Cached files that should survive app restarts.
+ // Apps should not rely on the OS to delete files in here.
+ cacheDirectory: null,
+ // Android: the application space on external storage.
+ externalApplicationStorageDirectory: null,
+ // Android: Where to put app-specific data files on external storage.
+ externalDataDirectory: null,
+ // Android: the application cache on external storage.
+ externalCacheDirectory: null,
+ // Android: the external storage (SD card) root.
+ externalRootDirectory: null,
+ // iOS: Temp directory that the OS can clear at will.
+ tempDirectory: null,
+ // iOS: Holds app-specific files that should be synced (e.g. to iCloud).
+ syncedDataDirectory: null,
+ // iOS: Files private to the app, but that are meaningful to other applciations (e.g. Office files)
+ documentsDirectory: null,
+ // BlackBerry10: Files globally available to all apps
+ sharedDirectory: null
+};
+
+channel.waitForInitialization('onFileSystemPathsReady');
+channel.onCordovaReady.subscribe(function() {
+ function after(paths) {
+ for (var k in paths) {
+ exports.file[k] = paths[k];
+ }
+ channel.initializationComplete('onFileSystemPathsReady');
+ }
+ exec(after, null, 'File', 'requestAllPaths', []);
+});
+
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js
new file mode 100644
index 0000000..1610b64
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js
@@ -0,0 +1,46 @@
+cordova.define("cordova-plugin-file.fileSystems-roots", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+// Map of fsName -> FileSystem.
+var fsMap = null;
+var FileSystem = require('./FileSystem');
+var exec = require('cordova/exec');
+
+// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.
+require('./fileSystems').getFs = function(name, callback) {
+ if (fsMap) {
+ callback(fsMap[name]);
+ } else {
+ exec(success, null, "File", "requestAllFileSystems", []);
+ function success(response) {
+ fsMap = {};
+ for (var i = 0; i < response.length; ++i) {
+ var fsRoot = response[i];
+ var fs = new FileSystem(fsRoot.filesystemName, fsRoot);
+ fsMap[fs.name] = fs;
+ }
+ callback(fsMap[name]);
+ }
+ }
+};
+
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems.js
new file mode 100644
index 0000000..2b8084b
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems.js
@@ -0,0 +1,27 @@
+cordova.define("cordova-plugin-file.fileSystems", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+// Overridden by Android, BlackBerry 10 and iOS to populate fsMap.
+module.exports.getFs = function(name, callback) {
+ callback(null);
+};
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/requestFileSystem.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/requestFileSystem.js
new file mode 100644
index 0000000..6626acc
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/requestFileSystem.js
@@ -0,0 +1,78 @@
+cordova.define("cordova-plugin-file.requestFileSystem", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+//For browser platform: not all browsers use this file.
+function checkBrowser() {
+ if (cordova.platformId === "browser" && navigator.userAgent.search(/Chrome/) > 0) {
+ var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+ module.exports = requestFileSystem;
+ return;
+ }
+}
+checkBrowser();
+
+var argscheck = require('cordova/argscheck'),
+ FileError = require('./FileError'),
+ FileSystem = require('./FileSystem'),
+ exec = require('cordova/exec');
+var fileSystems = require('./fileSystems');
+
+/**
+ * Request a file system in which to store application data.
+ * @param type local file system type
+ * @param size indicates how much storage space, in bytes, the application expects to need
+ * @param successCallback invoked with a FileSystem object
+ * @param errorCallback invoked if error occurs retrieving file system
+ */
+var requestFileSystem = function(type, size, successCallback, errorCallback) {
+ argscheck.checkArgs('nnFF', 'requestFileSystem', arguments);
+ var fail = function(code) {
+ errorCallback && errorCallback(new FileError(code));
+ };
+
+ if (type < 0) {
+ fail(FileError.SYNTAX_ERR);
+ } else {
+ // if successful, return a FileSystem object
+ var success = function(file_system) {
+ if (file_system) {
+ if (successCallback) {
+ fileSystems.getFs(file_system.name, function(fs) {
+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)
+ if (!fs) {
+ fs = new FileSystem(file_system.name, file_system.root);
+ }
+ successCallback(fs);
+ });
+ }
+ }
+ else {
+ // no FileSystem object returned
+ fail(FileError.NOT_FOUND_ERR);
+ }
+ };
+ exec(success, fail, "File", "requestFileSystem", [type, size]);
+ }
+};
+
+module.exports = requestFileSystem;
+
+});
diff --git a/platforms/android/platform_www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js b/platforms/android/platform_www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js
new file mode 100644
index 0000000..791a005
--- /dev/null
+++ b/platforms/android/platform_www/plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js
@@ -0,0 +1,89 @@
+cordova.define("cordova-plugin-file.resolveLocalFileSystemURI", function(require, exports, module) { /*
+ *
+ * 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.
+ *
+*/
+
+//For browser platform: not all browsers use overrided `resolveLocalFileSystemURL`.
+function checkBrowser() {
+ if (cordova.platformId === "browser" && navigator.userAgent.search(/Chrome/) > 0) {
+ var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+ module.exports = requestFileSystem;
+ return;
+ }
+}
+checkBrowser();
+
+var argscheck = require('cordova/argscheck'),
+ DirectoryEntry = require('./DirectoryEntry'),
+ FileEntry = require('./FileEntry'),
+ FileError = require('./FileError'),
+ exec = require('cordova/exec');
+var fileSystems = require('./fileSystems');
+
+/**
+ * Look up file system Entry referred to by local URI.
+ * @param {DOMString} uri URI referring to a local file or directory
+ * @param successCallback invoked with Entry object corresponding to URI
+ * @param errorCallback invoked if error occurs retrieving file system entry
+ */
+module.exports.resolveLocalFileSystemURL = function(uri, successCallback, errorCallback) {
+ argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);
+ // error callback
+ var fail = function(error) {
+ errorCallback && errorCallback(new FileError(error));
+ };
+ // sanity check for 'not:valid:filename' or '/not:valid:filename'
+ // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /.
+ if(!uri || uri.split(":").length > 2) {
+ setTimeout( function() {
+ fail(FileError.ENCODING_ERR);
+ },0);
+ return;
+ }
+ // if successful, return either a file or directory entry
+ var success = function(entry) {
+ if (entry) {
+ if (successCallback) {
+ // create appropriate Entry object
+ var fsName = entry.filesystemName || (entry.filesystem && entry.filesystem.name) || (entry.filesystem == window.PERSISTENT ? 'persistent' : 'temporary');
+ fileSystems.getFs(fsName, function(fs) {
+ // This should happen only on platforms that haven't implemented requestAllFileSystems (windows)
+ if (!fs) {
+ fs = new FileSystem(fsName, {name:"", fullPath:"/"});
+ }
+ var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);
+ successCallback(result);
+ });
+ }
+ }
+ else {
+ // no Entry object returned
+ fail(FileError.NOT_FOUND_ERR);
+ }
+ };
+
+ exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]);
+};
+
+module.exports.resolveLocalFileSystemURI = function() {
+ console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.");
+ module.exports.resolveLocalFileSystemURL.apply(this, arguments);
+};
+
+});
diff --git a/platforms/android/res/xml/config.xml b/platforms/android/res/xml/config.xml
index 9213a81..517cf14 100644
--- a/platforms/android/res/xml/config.xml
+++ b/platforms/android/res/xml/config.xml
@@ -26,6 +26,14 @@
+
+
+
+
+
+
+
+
diff --git a/platforms/android/src/org/apache/cordova/file/AssetFilesystem.java b/platforms/android/src/org/apache/cordova/file/AssetFilesystem.java
new file mode 100644
index 0000000..f501b27
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/AssetFilesystem.java
@@ -0,0 +1,283 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.content.res.AssetManager;
+import android.net.Uri;
+import android.util.Log;
+
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+public class AssetFilesystem extends Filesystem {
+
+ private final AssetManager assetManager;
+
+ // A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne.
+ // See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow
+ private static Object listCacheLock = new Object();
+ private static boolean listCacheFromFile;
+ private static Map listCache;
+ private static Map lengthCache;
+
+ private void lazyInitCaches() {
+ synchronized (listCacheLock) {
+ if (listCache == null) {
+ ObjectInputStream ois = null;
+ try {
+ ois = new ObjectInputStream(assetManager.open("cdvasset.manifest"));
+ listCache = (Map) ois.readObject();
+ lengthCache = (Map) ois.readObject();
+ listCacheFromFile = true;
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ // Asset manifest won't exist if the gradle hook isn't set up correctly.
+ } finally {
+ if (ois != null) {
+ try {
+ ois.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ if (listCache == null) {
+ Log.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow.");
+ listCache = new HashMap();
+ }
+ }
+ }
+ }
+
+ private String[] listAssets(String assetPath) throws IOException {
+ if (assetPath.startsWith("/")) {
+ assetPath = assetPath.substring(1);
+ }
+ lazyInitCaches();
+ String[] ret = listCache.get(assetPath);
+ if (ret == null) {
+ if (listCacheFromFile) {
+ ret = new String[0];
+ } else {
+ ret = assetManager.list(assetPath);
+ listCache.put(assetPath, ret);
+ }
+ }
+ return ret;
+ }
+
+ private long getAssetSize(String assetPath) throws FileNotFoundException {
+ if (assetPath.startsWith("/")) {
+ assetPath = assetPath.substring(1);
+ }
+ lazyInitCaches();
+ if (lengthCache != null) {
+ Long ret = lengthCache.get(assetPath);
+ if (ret == null) {
+ throw new FileNotFoundException("Asset not found: " + assetPath);
+ }
+ return ret;
+ }
+ CordovaResourceApi.OpenForReadResult offr = null;
+ try {
+ offr = resourceApi.openForRead(nativeUriForFullPath(assetPath));
+ long length = offr.length;
+ if (length < 0) {
+ // available() doesn't always yield the file size, but for assets it does.
+ length = offr.inputStream.available();
+ }
+ return length;
+ } catch (IOException e) {
+ throw new FileNotFoundException("File not found: " + assetPath);
+ } finally {
+ if (offr != null) {
+ try {
+ offr.inputStream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+
+ public AssetFilesystem(AssetManager assetManager, CordovaResourceApi resourceApi) {
+ super(Uri.parse("file:///android_asset/"), "assets", resourceApi);
+ this.assetManager = assetManager;
+ }
+
+ @Override
+ public Uri toNativeUri(LocalFilesystemURL inputURL) {
+ return nativeUriForFullPath(inputURL.path);
+ }
+
+ @Override
+ public LocalFilesystemURL toLocalUri(Uri inputURL) {
+ if (!"file".equals(inputURL.getScheme())) {
+ return null;
+ }
+ File f = new File(inputURL.getPath());
+ // Removes and duplicate /s (e.g. file:///a//b/c)
+ Uri resolvedUri = Uri.fromFile(f);
+ String rootUriNoTrailingSlash = rootUri.getEncodedPath();
+ rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
+ if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
+ return null;
+ }
+ String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
+ // Strip leading slash
+ if (!subPath.isEmpty()) {
+ subPath = subPath.substring(1);
+ }
+ Uri.Builder b = new Uri.Builder()
+ .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
+ .authority("localhost")
+ .path(name);
+ if (!subPath.isEmpty()) {
+ b.appendEncodedPath(subPath);
+ }
+ if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
+ // Add trailing / for directories.
+ b.appendEncodedPath("");
+ }
+ return LocalFilesystemURL.parse(b.build());
+ }
+
+ private boolean isDirectory(String assetPath) {
+ try {
+ return listAssets(assetPath).length != 0;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ String pathNoSlashes = inputURL.path.substring(1);
+ if (pathNoSlashes.endsWith("/")) {
+ pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
+ }
+
+ String[] files;
+ try {
+ files = listAssets(pathNoSlashes);
+ } catch (IOException e) {
+ throw new FileNotFoundException();
+ }
+
+ LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
+ for (int i = 0; i < files.length; ++i) {
+ entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
+ }
+ return entries;
+ }
+
+ @Override
+ public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
+ String path, JSONObject options, boolean directory)
+ throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ if (options != null && options.optBoolean("create")) {
+ throw new UnsupportedOperationException("Assets are read-only");
+ }
+
+ // Check whether the supplied path is absolute or relative
+ if (directory && !path.endsWith("/")) {
+ path += "/";
+ }
+
+ LocalFilesystemURL requestedURL;
+ if (path.startsWith("/")) {
+ requestedURL = localUrlforFullPath(normalizePath(path));
+ } else {
+ requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
+ }
+
+ // Throws a FileNotFoundException if it doesn't exist.
+ getFileMetadataForLocalURL(requestedURL);
+
+ boolean isDir = isDirectory(requestedURL.path);
+ if (directory && !isDir) {
+ throw new TypeMismatchException("path doesn't exist or is file");
+ } else if (!directory && isDir) {
+ throw new TypeMismatchException("path doesn't exist or is directory");
+ }
+
+ // Return the directory
+ return makeEntryForURL(requestedURL);
+ }
+
+ @Override
+ public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ JSONObject metadata = new JSONObject();
+ long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path);
+ try {
+ metadata.put("size", size);
+ metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL)));
+ metadata.put("name", new File(inputURL.path).getName());
+ metadata.put("fullPath", inputURL.path);
+ metadata.put("lastModifiedDate", 0);
+ } catch (JSONException e) {
+ return null;
+ }
+ return metadata;
+ }
+
+ @Override
+ public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
+ return false;
+ }
+
+ @Override
+ long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+ @Override
+ long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+ @Override
+ String filesystemPathForURL(LocalFilesystemURL url) {
+ return null;
+ }
+
+ @Override
+ LocalFilesystemURL URLforFilesystemPath(String path) {
+ return null;
+ }
+
+ @Override
+ boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+ @Override
+ boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+}
diff --git a/platforms/android/src/org/apache/cordova/file/ContentFilesystem.java b/platforms/android/src/org/apache/cordova/file/ContentFilesystem.java
new file mode 100644
index 0000000..eab0b03
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/ContentFilesystem.java
@@ -0,0 +1,215 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.MediaStore;
+import android.provider.OpenableColumns;
+
+public class ContentFilesystem extends Filesystem {
+
+ private final Context context;
+
+ public ContentFilesystem(Context context, CordovaResourceApi resourceApi) {
+ super(Uri.parse("content://"), "content", resourceApi);
+ this.context = context;
+ }
+
+ @Override
+ public Uri toNativeUri(LocalFilesystemURL inputURL) {
+ String authorityAndPath = inputURL.uri.getEncodedPath().substring(this.name.length() + 2);
+ if (authorityAndPath.length() < 2) {
+ return null;
+ }
+ String ret = "content://" + authorityAndPath;
+ String query = inputURL.uri.getEncodedQuery();
+ if (query != null) {
+ ret += '?' + query;
+ }
+ String frag = inputURL.uri.getEncodedFragment();
+ if (frag != null) {
+ ret += '#' + frag;
+ }
+ return Uri.parse(ret);
+ }
+
+ @Override
+ public LocalFilesystemURL toLocalUri(Uri inputURL) {
+ if (!"content".equals(inputURL.getScheme())) {
+ return null;
+ }
+ String subPath = inputURL.getEncodedPath();
+ if (subPath.length() > 0) {
+ subPath = subPath.substring(1);
+ }
+ Uri.Builder b = new Uri.Builder()
+ .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
+ .authority("localhost")
+ .path(name)
+ .appendPath(inputURL.getAuthority());
+ if (subPath.length() > 0) {
+ b.appendEncodedPath(subPath);
+ }
+ Uri localUri = b.encodedQuery(inputURL.getEncodedQuery())
+ .encodedFragment(inputURL.getEncodedFragment())
+ .build();
+ return LocalFilesystemURL.parse(localUri);
+ }
+
+ @Override
+ public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
+ String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
+ throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead.");
+ }
+
+ @Override
+ public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL)
+ throws NoModificationAllowedException {
+ Uri contentUri = toNativeUri(inputURL);
+ try {
+ context.getContentResolver().delete(contentUri, null, null);
+ } catch (UnsupportedOperationException t) {
+ // Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
+ // The ContentResolver applies only when the file was registered in the
+ // first case, which is generally only the case with images.
+ throw new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL)
+ throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Cannot remove content url");
+ }
+
+ @Override
+ public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead.");
+ }
+
+ @Override
+ public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ long size = -1;
+ long lastModified = 0;
+ Uri nativeUri = toNativeUri(inputURL);
+ String mimeType = resourceApi.getMimeType(nativeUri);
+ Cursor cursor = openCursorForURL(nativeUri);
+ try {
+ if (cursor != null && cursor.moveToFirst()) {
+ size = resourceSizeForCursor(cursor);
+ lastModified = lastModifiedDateForCursor(cursor);
+ } else {
+ // Some content providers don't support cursors at all!
+ CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri);
+ size = offr.length;
+ }
+ } catch (IOException e) {
+ throw new FileNotFoundException();
+ } finally {
+ if (cursor != null)
+ cursor.close();
+ }
+
+ JSONObject metadata = new JSONObject();
+ try {
+ metadata.put("size", size);
+ metadata.put("type", mimeType);
+ metadata.put("name", name);
+ metadata.put("fullPath", inputURL.path);
+ metadata.put("lastModifiedDate", lastModified);
+ } catch (JSONException e) {
+ return null;
+ }
+ return metadata;
+ }
+
+ @Override
+ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
+ int offset, boolean isBinary) throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Couldn't write to file given its content URI");
+ }
+ @Override
+ public long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
+ throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
+ }
+
+ protected Cursor openCursorForURL(Uri nativeUri) {
+ ContentResolver contentResolver = context.getContentResolver();
+ try {
+ return contentResolver.query(nativeUri, null, null, null, null);
+ } catch (UnsupportedOperationException e) {
+ return null;
+ }
+ }
+
+ private Long resourceSizeForCursor(Cursor cursor) {
+ int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
+ if (columnIndex != -1) {
+ String sizeStr = cursor.getString(columnIndex);
+ if (sizeStr != null) {
+ return Long.parseLong(sizeStr);
+ }
+ }
+ return null;
+ }
+
+ protected Long lastModifiedDateForCursor(Cursor cursor) {
+ final String[] LOCAL_FILE_PROJECTION = { MediaStore.MediaColumns.DATE_MODIFIED };
+ int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
+ if (columnIndex != -1) {
+ String dateStr = cursor.getString(columnIndex);
+ if (dateStr != null) {
+ return Long.parseLong(dateStr);
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public String filesystemPathForURL(LocalFilesystemURL url) {
+ File f = resourceApi.mapUriToFile(toNativeUri(url));
+ return f == null ? null : f.getAbsolutePath();
+ }
+
+ @Override
+ public LocalFilesystemURL URLforFilesystemPath(String path) {
+ // Returns null as we don't support reverse mapping back to content:// URLs
+ return null;
+ }
+
+ @Override
+ public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
+ return true;
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/file/DirectoryManager.java b/platforms/android/src/org/apache/cordova/file/DirectoryManager.java
new file mode 100644
index 0000000..c2d1278
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/DirectoryManager.java
@@ -0,0 +1,133 @@
+/*
+ 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.
+*/
+package org.apache.cordova.file;
+
+import android.os.Environment;
+import android.os.StatFs;
+
+import java.io.File;
+
+/**
+ * This class provides file directory utilities.
+ * All file operations are performed on the SD card.
+ *
+ * It is used by the FileUtils class.
+ */
+public class DirectoryManager {
+
+ @SuppressWarnings("unused")
+ private static final String LOG_TAG = "DirectoryManager";
+
+ /**
+ * Determine if a file or directory exists.
+ * @param name The name of the file to check.
+ * @return T=exists, F=not found
+ */
+ public static boolean testFileExists(String name) {
+ boolean status;
+
+ // If SD card exists
+ if ((testSaveLocationExists()) && (!name.equals(""))) {
+ File path = Environment.getExternalStorageDirectory();
+ File newPath = constructFilePaths(path.toString(), name);
+ status = newPath.exists();
+ }
+ // If no SD card
+ else {
+ status = false;
+ }
+ return status;
+ }
+
+ /**
+ * Get the free disk space
+ *
+ * @return Size in KB or -1 if not available
+ */
+ public static long getFreeDiskSpace(boolean checkInternal) {
+ String status = Environment.getExternalStorageState();
+ long freeSpace = 0;
+
+ // If SD card exists
+ if (status.equals(Environment.MEDIA_MOUNTED)) {
+ freeSpace = freeSpaceCalculation(Environment.getExternalStorageDirectory().getPath());
+ }
+ else if (checkInternal) {
+ freeSpace = freeSpaceCalculation("/");
+ }
+ // If no SD card and we haven't been asked to check the internal directory then return -1
+ else {
+ return -1;
+ }
+
+ return freeSpace;
+ }
+
+ /**
+ * Given a path return the number of free KB
+ *
+ * @param path to the file system
+ * @return free space in KB
+ */
+ private static long freeSpaceCalculation(String path) {
+ StatFs stat = new StatFs(path);
+ long blockSize = stat.getBlockSize();
+ long availableBlocks = stat.getAvailableBlocks();
+ return availableBlocks * blockSize / 1024;
+ }
+
+ /**
+ * Determine if SD card exists.
+ *
+ * @return T=exists, F=not found
+ */
+ public static boolean testSaveLocationExists() {
+ String sDCardStatus = Environment.getExternalStorageState();
+ boolean status;
+
+ // If SD card is mounted
+ if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
+ status = true;
+ }
+
+ // If no SD card
+ else {
+ status = false;
+ }
+ return status;
+ }
+
+ /**
+ * Create a new file object from two file paths.
+ *
+ * @param file1 Base file path
+ * @param file2 Remaining file path
+ * @return File object
+ */
+ private static File constructFilePaths (String file1, String file2) {
+ File newPath;
+ if (file2.startsWith(file1)) {
+ newPath = new File(file2);
+ }
+ else {
+ newPath = new File(file1 + "/" + file2);
+ }
+ return newPath;
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/file/EncodingException.java b/platforms/android/src/org/apache/cordova/file/EncodingException.java
new file mode 100644
index 0000000..e9e1653
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/EncodingException.java
@@ -0,0 +1,29 @@
+/*
+ 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.
+*/
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class EncodingException extends Exception {
+
+ public EncodingException(String message) {
+ super(message);
+ }
+
+}
diff --git a/platforms/android/src/org/apache/cordova/file/FileExistsException.java b/platforms/android/src/org/apache/cordova/file/FileExistsException.java
new file mode 100644
index 0000000..5c4d83d
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/FileExistsException.java
@@ -0,0 +1,29 @@
+/*
+ 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.
+*/
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class FileExistsException extends Exception {
+
+ public FileExistsException(String msg) {
+ super(msg);
+ }
+
+}
diff --git a/platforms/android/src/org/apache/cordova/file/FileUtils.java b/platforms/android/src/org/apache/cordova/file/FileUtils.java
new file mode 100644
index 0000000..c90a61d
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/FileUtils.java
@@ -0,0 +1,1022 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.app.Activity;
+import android.content.Context;
+import android.net.Uri;
+import android.os.Environment;
+import android.util.Base64;
+import android.util.Log;
+
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaInterface;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaWebView;
+import org.apache.cordova.PluginResult;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+
+/**
+ * This class provides file and directory services to JavaScript.
+ */
+public class FileUtils extends CordovaPlugin {
+ private static final String LOG_TAG = "FileUtils";
+
+ public static int NOT_FOUND_ERR = 1;
+ public static int SECURITY_ERR = 2;
+ public static int ABORT_ERR = 3;
+
+ public static int NOT_READABLE_ERR = 4;
+ public static int ENCODING_ERR = 5;
+ public static int NO_MODIFICATION_ALLOWED_ERR = 6;
+ public static int INVALID_STATE_ERR = 7;
+ public static int SYNTAX_ERR = 8;
+ public static int INVALID_MODIFICATION_ERR = 9;
+ public static int QUOTA_EXCEEDED_ERR = 10;
+ public static int TYPE_MISMATCH_ERR = 11;
+ public static int PATH_EXISTS_ERR = 12;
+
+ public static int UNKNOWN_ERR = 1000;
+
+ private boolean configured = false;
+
+ // This field exists only to support getEntry, below, which has been deprecated
+ private static FileUtils filePlugin;
+
+ private interface FileOp {
+ void run(JSONArray args) throws Exception;
+ }
+
+ private ArrayList filesystems;
+
+ public void registerFilesystem(Filesystem fs) {
+ if (fs != null && filesystemForName(fs.name)== null) {
+ this.filesystems.add(fs);
+ }
+ }
+
+ private Filesystem filesystemForName(String name) {
+ for (Filesystem fs:filesystems) {
+ if (fs != null && fs.name != null && fs.name.equals(name)) {
+ return fs;
+ }
+ }
+ return null;
+ }
+
+ protected String[] getExtraFileSystemsPreference(Activity activity) {
+ String fileSystemsStr = preferences.getString("androidextrafilesystems", "files,files-external,documents,sdcard,cache,cache-external,root");
+ return fileSystemsStr.split(",");
+ }
+
+ protected void registerExtraFileSystems(String[] filesystems, HashMap availableFileSystems) {
+ HashSet installedFileSystems = new HashSet();
+
+ /* Register filesystems in order */
+ for (String fsName : filesystems) {
+ if (!installedFileSystems.contains(fsName)) {
+ String fsRoot = availableFileSystems.get(fsName);
+ if (fsRoot != null) {
+ File newRoot = new File(fsRoot);
+ if (newRoot.mkdirs() || newRoot.isDirectory()) {
+ registerFilesystem(new LocalFilesystem(fsName, webView.getContext(), webView.getResourceApi(), newRoot));
+ installedFileSystems.add(fsName);
+ } else {
+ Log.d(LOG_TAG, "Unable to create root dir for filesystem \"" + fsName + "\", skipping");
+ }
+ } else {
+ Log.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName);
+ }
+ }
+ }
+ }
+
+ protected HashMap getAvailableFileSystems(Activity activity) {
+ Context context = activity.getApplicationContext();
+ HashMap availableFileSystems = new HashMap();
+
+ availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
+ availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
+ availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
+ availableFileSystems.put("root", "/");
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ try {
+ availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
+ availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
+ availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
+ }
+ catch(NullPointerException e) {
+ Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
+ }
+ }
+
+ return availableFileSystems;
+ }
+
+ @Override
+ public void initialize(CordovaInterface cordova, CordovaWebView webView) {
+ super.initialize(cordova, webView);
+ this.filesystems = new ArrayList();
+
+ String tempRoot = null;
+ String persistentRoot = null;
+
+ Activity activity = cordova.getActivity();
+ String packageName = activity.getPackageName();
+
+ String location = preferences.getString("androidpersistentfilelocation", "internal");
+
+ tempRoot = activity.getCacheDir().getAbsolutePath();
+ if ("internal".equalsIgnoreCase(location)) {
+ persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
+ this.configured = true;
+ } else if ("compatibility".equalsIgnoreCase(location)) {
+ /*
+ * Fall-back to compatibility mode -- this is the logic implemented in
+ * earlier versions of this plugin, and should be maintained here so
+ * that apps which were originally deployed with older versions of the
+ * plugin can continue to provide access to files stored under those
+ * versions.
+ */
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
+ tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() +
+ "/Android/data/" + packageName + "/cache/";
+ } else {
+ persistentRoot = "/data/data/" + packageName;
+ }
+ this.configured = true;
+ }
+
+ if (this.configured) {
+ // Create the directories if they don't exist.
+ File tmpRootFile = new File(tempRoot);
+ File persistentRootFile = new File(persistentRoot);
+ tmpRootFile.mkdirs();
+ persistentRootFile.mkdirs();
+
+ // Register initial filesystems
+ // Note: The temporary and persistent filesystems need to be the first two
+ // registered, so that they will match window.TEMPORARY and window.PERSISTENT,
+ // per spec.
+ this.registerFilesystem(new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile));
+ this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(), webView.getResourceApi(), persistentRootFile));
+ this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi()));
+ this.registerFilesystem(new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi()));
+
+ registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));
+
+ // Initialize static plugin reference for deprecated getEntry method
+ if (filePlugin == null) {
+ FileUtils.filePlugin = this;
+ }
+ } else {
+ Log.e(LOG_TAG, "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
+ activity.finish();
+ }
+ }
+
+ public static FileUtils getFilePlugin() {
+ return filePlugin;
+ }
+
+ private Filesystem filesystemForURL(LocalFilesystemURL localURL) {
+ if (localURL == null) return null;
+ return filesystemForName(localURL.fsName);
+ }
+
+ @Override
+ public Uri remapUri(Uri uri) {
+ // Remap only cdvfile: URLs (not content:).
+ if (!LocalFilesystemURL.FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
+ return null;
+ }
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ return null;
+ }
+ String path = fs.filesystemPathForURL(inputURL);
+ if (path != null) {
+ return Uri.parse("file://" + fs.filesystemPathForURL(inputURL));
+ }
+ return null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ public boolean execute(String action, final String rawArgs, final CallbackContext callbackContext) {
+ if (!configured) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File plugin is not configured. Please see the README.md file for details on how to update config.xml"));
+ return true;
+ }
+ if (action.equals("testSaveLocationExists")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) {
+ boolean b = DirectoryManager.testSaveLocationExists();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getFreeDiskSpace")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) {
+ long l = DirectoryManager.getFreeDiskSpace(false);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("testFileExists")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException {
+ String fname=args.getString(0);
+ boolean b = DirectoryManager.testFileExists(fname);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("testDirectoryExists")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException {
+ String fname=args.getString(0);
+ boolean b = DirectoryManager.testFileExists(fname);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsText")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ String encoding = args.getString(1);
+ int start = args.getInt(2);
+ int end = args.getInt(3);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsDataURL")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ int start = args.getInt(1);
+ int end = args.getInt(2);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, null, -1);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsArrayBuffer")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ int start = args.getInt(1);
+ int end = args.getInt(2);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsBinaryString")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ int start = args.getInt(1);
+ int end = args.getInt(2);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("write")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
+ String fname=args.getString(0);
+ String data=args.getString(1);
+ int offset=args.getInt(2);
+ Boolean isBinary=args.getBoolean(3);
+ long fileSize = write(fname, data, offset, isBinary);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("truncate")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
+ String fname=args.getString(0);
+ int offset=args.getInt(1);
+ long fileSize = truncateFile(fname, offset);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("requestAllFileSystems")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws IOException, JSONException {
+ callbackContext.success(requestAllFileSystems());
+ }
+ }, rawArgs, callbackContext);
+ } else if (action.equals("requestAllPaths")) {
+ cordova.getThreadPool().execute(
+ new Runnable() {
+ public void run() {
+ try {
+ callbackContext.success(requestAllPaths());
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+ );
+ } else if (action.equals("requestFileSystem")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws IOException, JSONException {
+ int fstype=args.getInt(0);
+ long size = args.optLong(1);
+ if (size != 0 && size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
+ } else {
+ JSONObject obj = requestFileSystem(fstype);
+ callbackContext.success(obj);
+ }
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("resolveLocalFileSystemURI")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws IOException, JSONException {
+ String fname=args.getString(0);
+ JSONObject obj = resolveLocalFileSystemURI(fname);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getFileMetadata")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
+ String fname=args.getString(0);
+ JSONObject obj = getFileMetadata(fname);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getParent")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, IOException {
+ String fname=args.getString(0);
+ JSONObject obj = getParent(fname);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getDirectory")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ String dirname=args.getString(0);
+ String path=args.getString(1);
+ JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getFile")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ String dirname=args.getString(0);
+ String path=args.getString(1);
+ JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("remove")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, NoModificationAllowedException, InvalidModificationException, MalformedURLException {
+ String fname=args.getString(0);
+ boolean success = remove(fname);
+ if (success) {
+ callbackContext.success();
+ } else {
+ callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
+ }
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("removeRecursively")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException, NoModificationAllowedException {
+ String fname=args.getString(0);
+ boolean success = removeRecursively(fname);
+ if (success) {
+ callbackContext.success();
+ } else {
+ callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
+ }
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("moveTo")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
+ String fname=args.getString(0);
+ String newParent=args.getString(1);
+ String newName=args.getString(2);
+ JSONObject entry = transferTo(fname, newParent, newName, true);
+ callbackContext.success(entry);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("copyTo")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
+ String fname=args.getString(0);
+ String newParent=args.getString(1);
+ String newName=args.getString(2);
+ JSONObject entry = transferTo(fname, newParent, newName, false);
+ callbackContext.success(entry);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readEntries")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
+ String fname=args.getString(0);
+ JSONArray entries = readEntries(fname);
+ callbackContext.success(entries);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("_getLocalFilesystemPath")) {
+ // Internal method for testing: Get the on-disk location of a local filesystem url.
+ // [Currently used for testing file-transfer]
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
+ String localURLstr = args.getString(0);
+ String fname = filesystemPathForURL(localURLstr);
+ callbackContext.success(fname);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else {
+ return false;
+ }
+ return true;
+ }
+
+ public LocalFilesystemURL resolveNativeUri(Uri nativeUri) {
+ LocalFilesystemURL localURL = null;
+
+ // Try all installed filesystems. Return the best matching URL
+ // (determined by the shortest resulting URL)
+ for (Filesystem fs : filesystems) {
+ LocalFilesystemURL url = fs.toLocalUri(nativeUri);
+ if (url != null) {
+ // A shorter fullPath implies that the filesystem is a better
+ // match for the local path than the previous best.
+ if (localURL == null || (url.uri.toString().length() < localURL.toString().length())) {
+ localURL = url;
+ }
+ }
+ }
+ return localURL;
+ }
+
+ /*
+ * These two native-only methods can be used by other plugins to translate between
+ * device file system paths and URLs. By design, there is no direct JavaScript
+ * interface to these methods.
+ */
+
+ public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.filesystemPathForURL(inputURL);
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ public LocalFilesystemURL filesystemURLforLocalPath(String localPath) {
+ LocalFilesystemURL localURL = null;
+ int shortestFullPath = 0;
+
+ // Try all installed filesystems. Return the best matching URL
+ // (determined by the shortest resulting URL)
+ for (Filesystem fs: filesystems) {
+ LocalFilesystemURL url = fs.URLforFilesystemPath(localPath);
+ if (url != null) {
+ // A shorter fullPath implies that the filesystem is a better
+ // match for the local path than the previous best.
+ if (localURL == null || (url.path.length() < shortestFullPath)) {
+ localURL = url;
+ shortestFullPath = url.path.length();
+ }
+ }
+ }
+ return localURL;
+ }
+
+
+ /* helper to execute functions async and handle the result codes
+ *
+ */
+ private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext){
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ try {
+ JSONArray args = new JSONArray(rawArgs);
+ f.run(args);
+ } catch ( Exception e) {
+ if( e instanceof EncodingException){
+ callbackContext.error(FileUtils.ENCODING_ERR);
+ } else if(e instanceof FileNotFoundException) {
+ callbackContext.error(FileUtils.NOT_FOUND_ERR);
+ } else if(e instanceof FileExistsException) {
+ callbackContext.error(FileUtils.PATH_EXISTS_ERR);
+ } else if(e instanceof NoModificationAllowedException ) {
+ callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
+ } else if(e instanceof InvalidModificationException ) {
+ callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
+ } else if(e instanceof MalformedURLException ) {
+ callbackContext.error(FileUtils.ENCODING_ERR);
+ } else if(e instanceof IOException ) {
+ callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
+ } else if(e instanceof EncodingException ) {
+ callbackContext.error(FileUtils.ENCODING_ERR);
+ } else if(e instanceof TypeMismatchException ) {
+ callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
+ } else if(e instanceof JSONException ) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ } else {
+ e.printStackTrace();
+ callbackContext.error(FileUtils.UNKNOWN_ERR);
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Allows the user to look up the Entry for a file or directory referred to by a local URI.
+ *
+ * @param uriString of the file/directory to look up
+ * @return a JSONObject representing a Entry from the filesystem
+ * @throws MalformedURLException if the url is not valid
+ * @throws FileNotFoundException if the file does not exist
+ * @throws IOException if the user can't read the file
+ * @throws JSONException
+ */
+ private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException {
+ if (uriString == null) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ Uri uri = Uri.parse(uriString);
+
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
+ if (inputURL == null) {
+ /* Check for file://, content:// urls */
+ inputURL = resolveNativeUri(uri);
+ }
+
+ try {
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ if (fs.exists(inputURL)) {
+ return fs.getEntryForLocalURL(inputURL);
+ }
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ throw new FileNotFoundException();
+ }
+
+ /**
+ * Read the list of files from this directory.
+ *
+ * @return a JSONArray containing JSONObjects that represent Entry objects.
+ * @throws FileNotFoundException if the directory is not found.
+ * @throws JSONException
+ * @throws MalformedURLException
+ */
+ private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.readEntriesAtLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * A setup method that handles the move/copy of files/directories
+ *
+ * @param newName for the file directory to be called, if null use existing file name
+ * @param move if false do a copy, if true do a move
+ * @return a Entry object
+ * @throws NoModificationAllowedException
+ * @throws IOException
+ * @throws InvalidModificationException
+ * @throws EncodingException
+ * @throws JSONException
+ * @throws FileExistsException
+ */
+ private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
+ if (srcURLstr == null || destURLstr == null) {
+ // either no source or no destination provided
+ throw new FileNotFoundException();
+ }
+
+ LocalFilesystemURL srcURL = LocalFilesystemURL.parse(srcURLstr);
+ LocalFilesystemURL destURL = LocalFilesystemURL.parse(destURLstr);
+
+ Filesystem srcFs = this.filesystemForURL(srcURL);
+ Filesystem destFs = this.filesystemForURL(destURL);
+
+ // Check for invalid file name
+ if (newName != null && newName.contains(":")) {
+ throw new EncodingException("Bad file name");
+ }
+
+ return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move);
+ }
+
+ /**
+ * Deletes a directory and all of its contents, if any. In the event of an error
+ * [e.g. trying to delete a directory that contains a file that cannot be removed],
+ * some of the contents of the directory may be deleted.
+ * It is an error to attempt to delete the root directory of a filesystem.
+ *
+ * @return a boolean representing success of failure
+ * @throws FileExistsException
+ * @throws NoModificationAllowedException
+ * @throws MalformedURLException
+ */
+ private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ // You can't delete the root directory.
+ if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
+ throw new NoModificationAllowedException("You can't delete the root directory");
+ }
+
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.recursiveRemoveFileAtLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+
+ /**
+ * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty.
+ * It is an error to attempt to delete the root directory of a filesystem.
+ *
+ * @return a boolean representing success of failure
+ * @throws NoModificationAllowedException
+ * @throws InvalidModificationException
+ * @throws MalformedURLException
+ */
+ private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ // You can't delete the root directory.
+ if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
+
+ throw new NoModificationAllowedException("You can't delete the root directory");
+ }
+
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.removeFileAtLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * Creates or looks up a file.
+ *
+ * @param baseURLstr base directory
+ * @param path file/directory to lookup or create
+ * @param options specify whether to create or not
+ * @param directory if true look up directory, if false look up file
+ * @return a Entry object
+ * @throws FileExistsException
+ * @throws IOException
+ * @throws TypeMismatchException
+ * @throws EncodingException
+ * @throws JSONException
+ */
+ private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.getFileForLocalURL(inputURL, path, options, directory);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+
+ }
+
+ /**
+ * Look up the parent DirectoryEntry containing this Entry.
+ * If this Entry is the root of its filesystem, its parent is itself.
+ */
+ private JSONObject getParent(String baseURLstr) throws JSONException, IOException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.getParentForLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * Returns a File that represents the current state of the file that this FileEntry represents.
+ *
+ * @return returns a JSONObject represent a W3C File object
+ */
+ private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.getFileMetadataForLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * Requests a filesystem in which to store application data.
+ *
+ * @param type of file system requested
+ * @return a JSONObject representing the file system
+ * @throws IOException
+ * @throws JSONException
+ */
+ private JSONObject requestFileSystem(int type) throws IOException, JSONException {
+ JSONObject fs = new JSONObject();
+ Filesystem rootFs = null;
+ try {
+ rootFs = this.filesystems.get(type);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Pass null through
+ }
+ if (rootFs == null) {
+ throw new IOException("No filesystem of type requested");
+ }
+ fs.put("name", rootFs.name);
+ fs.put("root", rootFs.getRootEntry());
+ return fs;
+ }
+
+
+ /**
+ * Requests a filesystem in which to store application data.
+ *
+ * @return a JSONObject representing the file system
+ */
+ private JSONArray requestAllFileSystems() throws IOException, JSONException {
+ JSONArray ret = new JSONArray();
+ for (Filesystem fs : filesystems) {
+ ret.put(fs.getRootEntry());
+ }
+ return ret;
+ }
+
+ private static String toDirUrl(File f) {
+ return Uri.fromFile(f).toString() + '/';
+ }
+
+ private JSONObject requestAllPaths() throws JSONException {
+ Context context = cordova.getActivity();
+ JSONObject ret = new JSONObject();
+ ret.put("applicationDirectory", "file:///android_asset/");
+ ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
+ ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
+ ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ try {
+ ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
+ ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
+ ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
+ ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
+ }
+ catch(NullPointerException e) {
+ /* If external storage is unavailable, context.getExternal* returns null */
+ Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Returns a JSON object representing the given File. Internal APIs should be modified
+ * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
+ *
+ * @param file the File to convert
+ * @return a JSON representation of the given File
+ * @throws JSONException
+ */
+ public JSONObject getEntryForFile(File file) throws JSONException {
+ JSONObject entry;
+
+ for (Filesystem fs : filesystems) {
+ entry = fs.makeEntryForFile(file);
+ if (entry != null) {
+ return entry;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns a JSON object representing the given File. Deprecated, as this is only used by
+ * FileTransfer, and because it is a static method that should really be an instance method,
+ * since it depends on the actual filesystem roots in use. Internal APIs should be modified
+ * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
+ *
+ * @param file the File to convert
+ * @return a JSON representation of the given File
+ * @throws JSONException
+ */
+ @Deprecated
+ public static JSONObject getEntry(File file) throws JSONException {
+ if (getFilePlugin() != null) {
+ return getFilePlugin().getEntryForFile(file);
+ }
+ return null;
+ }
+
+ /**
+ * Read the contents of a file.
+ * This is done in a background thread; the result is sent to the callback.
+ *
+ * @param start Start position in the file.
+ * @param end End position to stop at (exclusive).
+ * @param callbackContext The context through which to send the result.
+ * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
+ * @param resultType The desired type of data to send to the callback.
+ * @return Contents of file.
+ */
+ public void readFileAs(final String srcURLstr, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) throws MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+
+ fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() {
+ public void handleData(InputStream inputStream, String contentType) {
+ try {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ final int BUFFER_SIZE = 8192;
+ byte[] buffer = new byte[BUFFER_SIZE];
+
+ for (;;) {
+ int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
+
+ if (bytesRead <= 0) {
+ break;
+ }
+ os.write(buffer, 0, bytesRead);
+ }
+
+ PluginResult result;
+ switch (resultType) {
+ case PluginResult.MESSAGE_TYPE_STRING:
+ result = new PluginResult(PluginResult.Status.OK, os.toString(encoding));
+ break;
+ case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
+ result = new PluginResult(PluginResult.Status.OK, os.toByteArray());
+ break;
+ case PluginResult.MESSAGE_TYPE_BINARYSTRING:
+ result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true);
+ break;
+ default: // Base64.
+ byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP);
+ String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
+ result = new PluginResult(PluginResult.Status.OK, s);
+ }
+
+ callbackContext.sendPluginResult(result);
+ } catch (IOException e) {
+ Log.d(LOG_TAG, e.getLocalizedMessage());
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
+ }
+ }
+ });
+
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ } catch (FileNotFoundException e) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
+ } catch (IOException e) {
+ Log.d(LOG_TAG, e.getLocalizedMessage());
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
+ }
+ }
+
+
+ /**
+ * Write contents of file.
+ *
+ * @param data The contents of the file.
+ * @param offset The position to begin writing the file.
+ * @param isBinary True if the file contents are base64-encoded binary data
+ */
+ /**/
+ public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+
+ long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); Log.d("TEST",srcURLstr + ": "+x); return x;
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+
+ }
+
+ /**
+ * Truncate the file to size
+ */
+ private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+
+ return fs.truncateFileAtURL(inputURL, size);
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/file/Filesystem.java b/platforms/android/src/org/apache/cordova/file/Filesystem.java
new file mode 100644
index 0000000..faf31d2
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/Filesystem.java
@@ -0,0 +1,325 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.net.Uri;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public abstract class Filesystem {
+
+ protected final Uri rootUri;
+ protected final CordovaResourceApi resourceApi;
+ public final String name;
+ private JSONObject rootEntry;
+
+ public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi) {
+ this.rootUri = rootUri;
+ this.name = name;
+ this.resourceApi = resourceApi;
+ }
+
+ public interface ReadFileCallback {
+ public void handleData(InputStream inputStream, String contentType) throws IOException;
+ }
+
+ public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) {
+ try {
+ String path = inputURL.path;
+ int end = path.endsWith("/") ? 1 : 0;
+ String[] parts = path.substring(0, path.length() - end).split("/+");
+ String fileName = parts[parts.length - 1];
+
+ JSONObject entry = new JSONObject();
+ entry.put("isFile", !inputURL.isDirectory);
+ entry.put("isDirectory", inputURL.isDirectory);
+ entry.put("name", fileName);
+ entry.put("fullPath", path);
+ // The file system can't be specified, as it would lead to an infinite loop,
+ // but the filesystem name can be.
+ entry.put("filesystemName", inputURL.fsName);
+ // Backwards compatibility
+ entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1);
+
+ String nativeUrlStr = nativeURL.toString();
+ if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) {
+ nativeUrlStr += "/";
+ }
+ entry.put("nativeURL", nativeUrlStr);
+ return entry;
+ } catch (JSONException e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+ }
+
+ public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) {
+ Uri nativeUri = toNativeUri(inputURL);
+ return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri);
+ }
+
+ public JSONObject makeEntryForNativeUri(Uri nativeUri) {
+ LocalFilesystemURL inputUrl = toLocalUri(nativeUri);
+ return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri);
+ }
+
+ public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
+ return makeEntryForURL(inputURL);
+ }
+
+ public JSONObject makeEntryForFile(File file) {
+ return makeEntryForNativeUri(Uri.fromFile(file));
+ }
+
+ abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path,
+ JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;
+
+ abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;
+
+ abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;
+
+ abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException;
+
+ public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ LocalFilesystemURL[] children = listChildren(inputURL);
+ JSONArray entries = new JSONArray();
+ if (children != null) {
+ for (LocalFilesystemURL url : children) {
+ entries.put(makeEntryForURL(url));
+ }
+ }
+ return entries;
+ }
+
+ abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;
+
+ public Uri getRootUri() {
+ return rootUri;
+ }
+
+ public boolean exists(LocalFilesystemURL inputURL) {
+ try {
+ getFileMetadataForLocalURL(inputURL);
+ } catch (FileNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
+
+ public Uri nativeUriForFullPath(String fullPath) {
+ Uri ret = null;
+ if (fullPath != null) {
+ String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
+ if (encodedPath.startsWith("/")) {
+ encodedPath = encodedPath.substring(1);
+ }
+ ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
+ }
+ return ret;
+ }
+
+ public LocalFilesystemURL localUrlforFullPath(String fullPath) {
+ Uri nativeUri = nativeUriForFullPath(fullPath);
+ if (nativeUri != null) {
+ return toLocalUri(nativeUri);
+ }
+ return null;
+ }
+
+ /**
+ * Removes multiple repeated //s, and collapses processes ../s.
+ */
+ protected static String normalizePath(String rawPath) {
+ // If this is an absolute path, trim the leading "/" and replace it later
+ boolean isAbsolutePath = rawPath.startsWith("/");
+ if (isAbsolutePath) {
+ rawPath = rawPath.replaceFirst("/+", "");
+ }
+ ArrayList components = new ArrayList(Arrays.asList(rawPath.split("/+")));
+ for (int index = 0; index < components.size(); ++index) {
+ if (components.get(index).equals("..")) {
+ components.remove(index);
+ if (index > 0) {
+ components.remove(index-1);
+ --index;
+ }
+ }
+ }
+ StringBuilder normalizedPath = new StringBuilder();
+ for(String component: components) {
+ normalizedPath.append("/");
+ normalizedPath.append(component);
+ }
+ if (isAbsolutePath) {
+ return normalizedPath.toString();
+ } else {
+ return normalizedPath.toString().substring(1);
+ }
+ }
+
+
+
+ public abstract Uri toNativeUri(LocalFilesystemURL inputURL);
+ public abstract LocalFilesystemURL toLocalUri(Uri inputURL);
+
+ public JSONObject getRootEntry() {
+ if (rootEntry == null) {
+ rootEntry = makeEntryForNativeUri(rootUri);
+ }
+ return rootEntry;
+ }
+
+ public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
+ Uri parentUri = inputURL.uri;
+ String parentPath = new File(inputURL.uri.getPath()).getParent();
+ if (!"/".equals(parentPath)) {
+ parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build();
+ }
+ return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri));
+ }
+
+ protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) {
+ // I know this looks weird but it is to work around a JSON bug.
+ if ("null".equals(newName) || "".equals(newName)) {
+ newName = srcURL.uri.getLastPathSegment();;
+ }
+
+ String newDest = destURL.uri.toString();
+ if (newDest.endsWith("/")) {
+ newDest = newDest + newName;
+ } else {
+ newDest = newDest + "/" + newName;
+ }
+ if (isDirectory) {
+ newDest += '/';
+ }
+ return LocalFilesystemURL.parse(newDest);
+ }
+
+ /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
+ * the destination URL on this filesystem, optionally with a new filename.
+ * If move is true, then this method should either perform an atomic move operation
+ * or remove the source file when finished.
+ */
+ public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
+ Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
+ // First, check to see that we can do it
+ if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
+ throw new NoModificationAllowedException("Cannot move file at source URL");
+ }
+ final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
+
+ Uri srcNativeUri = srcFs.toNativeUri(srcURL);
+
+ CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri);
+ OutputStream os = null;
+ try {
+ os = getOutputStreamForURL(destination);
+ } catch (IOException e) {
+ ofrr.inputStream.close();
+ throw e;
+ }
+ // Closes streams.
+ resourceApi.copyResource(ofrr, os);
+
+ if (move) {
+ srcFs.removeFileAtLocalURL(srcURL);
+ }
+ return getEntryForLocalURL(destination);
+ }
+
+ public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException {
+ return resourceApi.openOutputStream(toNativeUri(inputURL));
+ }
+
+ public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
+ ReadFileCallback readFileCallback) throws IOException {
+ CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL));
+ if (end < 0) {
+ end = ofrr.length;
+ }
+ long numBytesToRead = end - start;
+ try {
+ if (start > 0) {
+ ofrr.inputStream.skip(start);
+ }
+ InputStream inputStream = ofrr.inputStream;
+ if (end < ofrr.length) {
+ inputStream = new LimitedInputStream(inputStream, numBytesToRead);
+ }
+ readFileCallback.handleData(inputStream, ofrr.mimeType);
+ } finally {
+ ofrr.inputStream.close();
+ }
+ }
+
+ abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset,
+ boolean isBinary) throws NoModificationAllowedException, IOException;
+
+ abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
+ throws IOException, NoModificationAllowedException;
+
+ // This method should return null if filesystem urls cannot be mapped to paths
+ abstract String filesystemPathForURL(LocalFilesystemURL url);
+
+ abstract LocalFilesystemURL URLforFilesystemPath(String path);
+
+ abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);
+
+ protected class LimitedInputStream extends FilterInputStream {
+ long numBytesToRead;
+ public LimitedInputStream(InputStream in, long numBytesToRead) {
+ super(in);
+ this.numBytesToRead = numBytesToRead;
+ }
+ @Override
+ public int read() throws IOException {
+ if (numBytesToRead <= 0) {
+ return -1;
+ }
+ numBytesToRead--;
+ return in.read();
+ }
+ @Override
+ public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
+ if (numBytesToRead <= 0) {
+ return -1;
+ }
+ int bytesToRead = byteCount;
+ if (byteCount > numBytesToRead) {
+ bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here.
+ }
+ int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
+ numBytesToRead -= numBytesRead;
+ return numBytesRead;
+ }
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/file/InvalidModificationException.java b/platforms/android/src/org/apache/cordova/file/InvalidModificationException.java
new file mode 100644
index 0000000..8f6bec5
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/InvalidModificationException.java
@@ -0,0 +1,30 @@
+/*
+ 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.
+*/
+
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class InvalidModificationException extends Exception {
+
+ public InvalidModificationException(String message) {
+ super(message);
+ }
+
+}
diff --git a/platforms/android/src/org/apache/cordova/file/LocalFilesystem.java b/platforms/android/src/org/apache/cordova/file/LocalFilesystem.java
new file mode 100644
index 0000000..2c77596
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/LocalFilesystem.java
@@ -0,0 +1,505 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.os.Build;
+import android.os.Environment;
+import android.util.Base64;
+import android.net.Uri;
+import android.content.Context;
+import android.content.Intent;
+
+public class LocalFilesystem extends Filesystem {
+ private final Context context;
+
+ public LocalFilesystem(String name, Context context, CordovaResourceApi resourceApi, File fsRoot) {
+ super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi);
+ this.context = context;
+ }
+
+ public String filesystemPathForFullPath(String fullPath) {
+ return new File(rootUri.getPath(), fullPath).toString();
+ }
+
+ @Override
+ public String filesystemPathForURL(LocalFilesystemURL url) {
+ return filesystemPathForFullPath(url.path);
+ }
+
+ private String fullPathForFilesystemPath(String absolutePath) {
+ if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) {
+ return absolutePath.substring(rootUri.getPath().length() - 1);
+ }
+ return null;
+ }
+
+ @Override
+ public Uri toNativeUri(LocalFilesystemURL inputURL) {
+ return nativeUriForFullPath(inputURL.path);
+ }
+
+ @Override
+ public LocalFilesystemURL toLocalUri(Uri inputURL) {
+ if (!"file".equals(inputURL.getScheme())) {
+ return null;
+ }
+ File f = new File(inputURL.getPath());
+ // Removes and duplicate /s (e.g. file:///a//b/c)
+ Uri resolvedUri = Uri.fromFile(f);
+ String rootUriNoTrailingSlash = rootUri.getEncodedPath();
+ rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
+ if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
+ return null;
+ }
+ String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
+ // Strip leading slash
+ if (!subPath.isEmpty()) {
+ subPath = subPath.substring(1);
+ }
+ Uri.Builder b = new Uri.Builder()
+ .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
+ .authority("localhost")
+ .path(name);
+ if (!subPath.isEmpty()) {
+ b.appendEncodedPath(subPath);
+ }
+ if (f.isDirectory() || inputURL.getPath().endsWith("/")) {
+ // Add trailing / for directories.
+ b.appendEncodedPath("");
+ }
+ return LocalFilesystemURL.parse(b.build());
+ }
+
+ @Override
+ public LocalFilesystemURL URLforFilesystemPath(String path) {
+ return localUrlforFullPath(fullPathForFilesystemPath(path));
+ }
+
+ @Override
+ public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
+ String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ boolean create = false;
+ boolean exclusive = false;
+
+ if (options != null) {
+ create = options.optBoolean("create");
+ if (create) {
+ exclusive = options.optBoolean("exclusive");
+ }
+ }
+
+ // Check for a ":" character in the file to line up with BB and iOS
+ if (path.contains(":")) {
+ throw new EncodingException("This path has an invalid \":\" in it.");
+ }
+
+ LocalFilesystemURL requestedURL;
+
+ // Check whether the supplied path is absolute or relative
+ if (directory && !path.endsWith("/")) {
+ path += "/";
+ }
+ if (path.startsWith("/")) {
+ requestedURL = localUrlforFullPath(normalizePath(path));
+ } else {
+ requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
+ }
+
+ File fp = new File(this.filesystemPathForURL(requestedURL));
+
+ if (create) {
+ if (exclusive && fp.exists()) {
+ throw new FileExistsException("create/exclusive fails");
+ }
+ if (directory) {
+ fp.mkdir();
+ } else {
+ fp.createNewFile();
+ }
+ if (!fp.exists()) {
+ throw new FileExistsException("create fails");
+ }
+ }
+ else {
+ if (!fp.exists()) {
+ throw new FileNotFoundException("path does not exist");
+ }
+ if (directory) {
+ if (fp.isFile()) {
+ throw new TypeMismatchException("path doesn't exist or is file");
+ }
+ } else {
+ if (fp.isDirectory()) {
+ throw new TypeMismatchException("path doesn't exist or is directory");
+ }
+ }
+ }
+
+ // Return the directory
+ return makeEntryForURL(requestedURL);
+ }
+
+ @Override
+ public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException {
+
+ File fp = new File(filesystemPathForURL(inputURL));
+
+ // You can't delete a directory that is not empty
+ if (fp.isDirectory() && fp.list().length > 0) {
+ throw new InvalidModificationException("You can't delete a directory that is not empty.");
+ }
+
+ return fp.delete();
+ }
+
+ @Override
+ public boolean exists(LocalFilesystemURL inputURL) {
+ File fp = new File(filesystemPathForURL(inputURL));
+ return fp.exists();
+ }
+
+ @Override
+ public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException {
+ File directory = new File(filesystemPathForURL(inputURL));
+ return removeDirRecursively(directory);
+ }
+
+ protected boolean removeDirRecursively(File directory) throws FileExistsException {
+ if (directory.isDirectory()) {
+ for (File file : directory.listFiles()) {
+ removeDirRecursively(file);
+ }
+ }
+
+ if (!directory.delete()) {
+ throw new FileExistsException("could not delete: " + directory.getName());
+ } else {
+ return true;
+ }
+ }
+
+ @Override
+ public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ File fp = new File(filesystemPathForURL(inputURL));
+
+ if (!fp.exists()) {
+ // The directory we are listing doesn't exist so we should fail.
+ throw new FileNotFoundException();
+ }
+
+ File[] files = fp.listFiles();
+ if (files == null) {
+ // inputURL is a directory
+ return null;
+ }
+ LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
+ for (int i = 0; i < files.length; i++) {
+ entries[i] = URLforFilesystemPath(files[i].getPath());
+ }
+
+ return entries;
+ }
+
+ @Override
+ public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ File file = new File(filesystemPathForURL(inputURL));
+
+ if (!file.exists()) {
+ throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
+ }
+
+ JSONObject metadata = new JSONObject();
+ try {
+ // Ensure that directories report a size of 0
+ metadata.put("size", file.isDirectory() ? 0 : file.length());
+ metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file)));
+ metadata.put("name", file.getName());
+ metadata.put("fullPath", inputURL.path);
+ metadata.put("lastModifiedDate", file.lastModified());
+ } catch (JSONException e) {
+ return null;
+ }
+ return metadata;
+ }
+
+ private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException {
+ if (move) {
+ String realSrcPath = srcFs.filesystemPathForURL(srcURL);
+ if (realSrcPath != null) {
+ File srcFile = new File(realSrcPath);
+ if (srcFile.renameTo(destFile)) {
+ return;
+ }
+ // Trying to rename the file failed. Possibly because we moved across file system on the device.
+ }
+ }
+
+ CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL));
+ copyResource(offr, new FileOutputStream(destFile));
+
+ if (move) {
+ srcFs.removeFileAtLocalURL(srcURL);
+ }
+ }
+
+ private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
+ if (move) {
+ String realSrcPath = srcFs.filesystemPathForURL(srcURL);
+ if (realSrcPath != null) {
+ File srcDir = new File(realSrcPath);
+ // If the destination directory already exists and is empty then delete it. This is according to spec.
+ if (dstDir.exists()) {
+ if (dstDir.list().length > 0) {
+ throw new InvalidModificationException("directory is not empty");
+ }
+ dstDir.delete();
+ }
+ // Try to rename the directory
+ if (srcDir.renameTo(dstDir)) {
+ return;
+ }
+ // Trying to rename the file failed. Possibly because we moved across file system on the device.
+ }
+ }
+
+ if (dstDir.exists()) {
+ if (dstDir.list().length > 0) {
+ throw new InvalidModificationException("directory is not empty");
+ }
+ } else {
+ if (!dstDir.mkdir()) {
+ // If we can't create the directory then fail
+ throw new NoModificationAllowedException("Couldn't create the destination directory");
+ }
+ }
+
+ LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
+ for (LocalFilesystemURL childLocalUrl : children) {
+ File target = new File(dstDir, new File(childLocalUrl.path).getName());
+ if (childLocalUrl.isDirectory) {
+ copyDirectory(srcFs, childLocalUrl, target, false);
+ } else {
+ copyFile(srcFs, childLocalUrl, target, false);
+ }
+ }
+
+ if (move) {
+ srcFs.recursiveRemoveFileAtLocalURL(srcURL);
+ }
+ }
+
+ @Override
+ public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
+ Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
+
+ // Check to see if the destination directory exists
+ String newParent = this.filesystemPathForURL(destURL);
+ File destinationDir = new File(newParent);
+ if (!destinationDir.exists()) {
+ // The destination does not exist so we should fail.
+ throw new FileNotFoundException("The source does not exist");
+ }
+
+ // Figure out where we should be copying to
+ final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
+
+ Uri dstNativeUri = toNativeUri(destinationURL);
+ Uri srcNativeUri = srcFs.toNativeUri(srcURL);
+ // Check to see if source and destination are the same file
+ if (dstNativeUri.equals(srcNativeUri)) {
+ throw new InvalidModificationException("Can't copy onto itself");
+ }
+
+ if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
+ throw new InvalidModificationException("Source URL is read-only (cannot move)");
+ }
+
+ File destFile = new File(dstNativeUri.getPath());
+ if (destFile.exists()) {
+ if (!srcURL.isDirectory && destFile.isDirectory()) {
+ throw new InvalidModificationException("Can't copy/move a file to an existing directory");
+ } else if (srcURL.isDirectory && destFile.isFile()) {
+ throw new InvalidModificationException("Can't copy/move a directory to an existing file");
+ }
+ }
+
+ if (srcURL.isDirectory) {
+ // E.g. Copy /sdcard/myDir to /sdcard/myDir/backup
+ if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) {
+ throw new InvalidModificationException("Can't copy directory into itself");
+ }
+ copyDirectory(srcFs, srcURL, destFile, move);
+ } else {
+ copyFile(srcFs, srcURL, destFile, move);
+ }
+ return makeEntryForURL(destinationURL);
+ }
+
+ @Override
+ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
+ int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
+
+ boolean append = false;
+ if (offset > 0) {
+ this.truncateFileAtURL(inputURL, offset);
+ append = true;
+ }
+
+ byte[] rawData;
+ if (isBinary) {
+ rawData = Base64.decode(data, Base64.DEFAULT);
+ } else {
+ rawData = data.getBytes();
+ }
+ ByteArrayInputStream in = new ByteArrayInputStream(rawData);
+ try
+ {
+ byte buff[] = new byte[rawData.length];
+ String absolutePath = filesystemPathForURL(inputURL);
+ FileOutputStream out = new FileOutputStream(absolutePath, append);
+ try {
+ in.read(buff, 0, buff.length);
+ out.write(buff, 0, rawData.length);
+ out.flush();
+ } finally {
+ // Always close the output
+ out.close();
+ }
+ if (isPublicDirectory(absolutePath)) {
+ broadcastNewFile(Uri.fromFile(new File(absolutePath)));
+ }
+ }
+ catch (NullPointerException e)
+ {
+ // This is a bug in the Android implementation of the Java Stack
+ NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
+ throw realException;
+ }
+
+ return rawData.length;
+ }
+
+ private boolean isPublicDirectory(String absolutePath) {
+ // TODO: should expose a way to scan app's private files (maybe via a flag).
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ // Lollipop has a bug where SD cards are null.
+ for (File f : context.getExternalMediaDirs()) {
+ if(f != null && absolutePath.startsWith(f.getAbsolutePath())) {
+ return true;
+ }
+ }
+ }
+
+ String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
+ return absolutePath.startsWith(extPath);
+ }
+
+ /**
+ * Send broadcast of new file so files appear over MTP
+ */
+ private void broadcastNewFile(Uri nativeUri) {
+ Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri);
+ context.sendBroadcast(intent);
+ }
+
+ @Override
+ public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
+ File file = new File(filesystemPathForURL(inputURL));
+
+ if (!file.exists()) {
+ throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
+ }
+
+ RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
+ try {
+ if (raf.length() >= size) {
+ FileChannel channel = raf.getChannel();
+ channel.truncate(size);
+ return size;
+ }
+
+ return raf.length();
+ } finally {
+ raf.close();
+ }
+
+
+ }
+
+ @Override
+ public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
+ String path = filesystemPathForURL(inputURL);
+ File file = new File(path);
+ return file.exists();
+ }
+
+ // This is a copy & paste from CordovaResource API that is required since CordovaResourceApi
+ // has a bug pre-4.0.0.
+ // TODO: Once cordova-android@4.0.0 is released, delete this copy and make the plugin depend on
+ // 4.0.0 with an engine tag.
+ private static void copyResource(CordovaResourceApi.OpenForReadResult input, OutputStream outputStream) throws IOException {
+ try {
+ InputStream inputStream = input.inputStream;
+ if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
+ FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
+ FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
+ long offset = 0;
+ long length = input.length;
+ if (input.assetFd != null) {
+ offset = input.assetFd.getStartOffset();
+ }
+ // transferFrom()'s 2nd arg is a relative position. Need to set the absolute
+ // position first.
+ inChannel.position(offset);
+ outChannel.transferFrom(inChannel, 0, length);
+ } else {
+ final int BUFFER_SIZE = 8192;
+ byte[] buffer = new byte[BUFFER_SIZE];
+
+ for (;;) {
+ int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
+
+ if (bytesRead <= 0) {
+ break;
+ }
+ outputStream.write(buffer, 0, bytesRead);
+ }
+ }
+ } finally {
+ input.inputStream.close();
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ }
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/file/LocalFilesystemURL.java b/platforms/android/src/org/apache/cordova/file/LocalFilesystemURL.java
new file mode 100644
index 0000000..b96b6ee
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/LocalFilesystemURL.java
@@ -0,0 +1,64 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.net.Uri;
+
+public class LocalFilesystemURL {
+
+ public static final String FILESYSTEM_PROTOCOL = "cdvfile";
+
+ public final Uri uri;
+ public final String fsName;
+ public final String path;
+ public final boolean isDirectory;
+
+ private LocalFilesystemURL(Uri uri, String fsName, String fsPath, boolean isDirectory) {
+ this.uri = uri;
+ this.fsName = fsName;
+ this.path = fsPath;
+ this.isDirectory = isDirectory;
+ }
+
+ public static LocalFilesystemURL parse(Uri uri) {
+ if (!FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
+ return null;
+ }
+ String path = uri.getPath();
+ if (path.length() < 1) {
+ return null;
+ }
+ int firstSlashIdx = path.indexOf('/', 1);
+ if (firstSlashIdx < 0) {
+ return null;
+ }
+ String fsName = path.substring(1, firstSlashIdx);
+ path = path.substring(firstSlashIdx);
+ boolean isDirectory = path.charAt(path.length() - 1) == '/';
+ return new LocalFilesystemURL(uri, fsName, path, isDirectory);
+ }
+
+ public static LocalFilesystemURL parse(String uri) {
+ return parse(Uri.parse(uri));
+ }
+
+ public String toString() {
+ return uri.toString();
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/file/NoModificationAllowedException.java b/platforms/android/src/org/apache/cordova/file/NoModificationAllowedException.java
new file mode 100644
index 0000000..627eafb
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/NoModificationAllowedException.java
@@ -0,0 +1,29 @@
+/*
+ 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.
+*/
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class NoModificationAllowedException extends Exception {
+
+ public NoModificationAllowedException(String message) {
+ super(message);
+ }
+
+}
diff --git a/platforms/android/src/org/apache/cordova/file/TypeMismatchException.java b/platforms/android/src/org/apache/cordova/file/TypeMismatchException.java
new file mode 100644
index 0000000..1315f9a
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/file/TypeMismatchException.java
@@ -0,0 +1,30 @@
+/*
+ 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.
+*/
+
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class TypeMismatchException extends Exception {
+
+ public TypeMismatchException(String message) {
+ super(message);
+ }
+
+}
diff --git a/platforms/android/src/org/apache/cordova/filetransfer/FileProgressResult.java b/platforms/android/src/org/apache/cordova/filetransfer/FileProgressResult.java
new file mode 100644
index 0000000..76a7b13
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/filetransfer/FileProgressResult.java
@@ -0,0 +1,63 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Encapsulates in-progress status of uploading or downloading a file to a remote server.
+ */
+public class FileProgressResult {
+
+ private boolean lengthComputable = false; // declares whether total is known
+ private long loaded = 0; // bytes sent so far
+ private long total = 0; // bytes total, if known
+
+ public boolean getLengthComputable() {
+ return lengthComputable;
+ }
+
+ public void setLengthComputable(boolean computable) {
+ this.lengthComputable = computable;
+ }
+
+ public long getLoaded() {
+ return loaded;
+ }
+
+ public void setLoaded(long bytes) {
+ this.loaded = bytes;
+ }
+
+ public long getTotal() {
+ return total;
+ }
+
+ public void setTotal(long bytes) {
+ this.total = bytes;
+ }
+
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{loaded:" + loaded +
+ ",total:" + total +
+ ",lengthComputable:" + (lengthComputable ? "true" : "false") + "}");
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/filetransfer/FileTransfer.java b/platforms/android/src/org/apache/cordova/filetransfer/FileTransfer.java
new file mode 100644
index 0000000..0efbd4e
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/filetransfer/FileTransfer.java
@@ -0,0 +1,1025 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
+import java.net.URLConnection;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.Inflater;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.cordova.Config;
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaResourceApi;
+import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
+import org.apache.cordova.PluginManager;
+import org.apache.cordova.PluginResult;
+import org.apache.cordova.Whitelist;
+import org.apache.cordova.file.FileUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.net.Uri;
+import android.os.Build;
+import android.util.Log;
+import android.webkit.CookieManager;
+
+public class FileTransfer extends CordovaPlugin {
+
+ private static final String LOG_TAG = "FileTransfer";
+ private static final String LINE_START = "--";
+ private static final String LINE_END = "\r\n";
+ private static final String BOUNDARY = "+++++";
+
+ public static int FILE_NOT_FOUND_ERR = 1;
+ public static int INVALID_URL_ERR = 2;
+ public static int CONNECTION_ERR = 3;
+ public static int ABORTED_ERR = 4;
+ public static int NOT_MODIFIED_ERR = 5;
+
+ private static HashMap activeRequests = new HashMap();
+ private static final int MAX_BUFFER_SIZE = 16 * 1024;
+
+ private static final class RequestContext {
+ String source;
+ String target;
+ File targetFile;
+ CallbackContext callbackContext;
+ HttpURLConnection connection;
+ boolean aborted;
+ RequestContext(String source, String target, CallbackContext callbackContext) {
+ this.source = source;
+ this.target = target;
+ this.callbackContext = callbackContext;
+ }
+ void sendPluginResult(PluginResult pluginResult) {
+ synchronized (this) {
+ if (!aborted) {
+ callbackContext.sendPluginResult(pluginResult);
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds an interface method to an InputStream to return the number of bytes
+ * read from the raw stream. This is used to track total progress against
+ * the HTTP Content-Length header value from the server.
+ */
+ private static abstract class TrackingInputStream extends FilterInputStream {
+ public TrackingInputStream(final InputStream in) {
+ super(in);
+ }
+ public abstract long getTotalRawBytesRead();
+ }
+
+ private static class ExposedGZIPInputStream extends GZIPInputStream {
+ public ExposedGZIPInputStream(final InputStream in) throws IOException {
+ super(in);
+ }
+ public Inflater getInflater() {
+ return inf;
+ }
+ }
+
+ /**
+ * Provides raw bytes-read tracking for a GZIP input stream. Reports the
+ * total number of compressed bytes read from the input, rather than the
+ * number of uncompressed bytes.
+ */
+ private static class TrackingGZIPInputStream extends TrackingInputStream {
+ private ExposedGZIPInputStream gzin;
+ public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException {
+ super(gzin);
+ this.gzin = gzin;
+ }
+ public long getTotalRawBytesRead() {
+ return gzin.getInflater().getBytesRead();
+ }
+ }
+
+ /**
+ * Provides simple total-bytes-read tracking for an existing InputStream
+ */
+ private static class SimpleTrackingInputStream extends TrackingInputStream {
+ private long bytesRead = 0;
+ public SimpleTrackingInputStream(InputStream stream) {
+ super(stream);
+ }
+
+ private int updateBytesRead(int newBytesRead) {
+ if (newBytesRead != -1) {
+ bytesRead += newBytesRead;
+ }
+ return newBytesRead;
+ }
+
+ @Override
+ public int read() throws IOException {
+ return updateBytesRead(super.read());
+ }
+
+ // Note: FilterInputStream delegates read(byte[] bytes) to the below method,
+ // so we don't override it or else double count (CB-5631).
+ @Override
+ public int read(byte[] bytes, int offset, int count) throws IOException {
+ return updateBytesRead(super.read(bytes, offset, count));
+ }
+
+ public long getTotalRawBytesRead() {
+ return bytesRead;
+ }
+ }
+
+ @Override
+ public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
+ if (action.equals("upload") || action.equals("download")) {
+ String source = args.getString(0);
+ String target = args.getString(1);
+
+ if (action.equals("upload")) {
+ upload(source, target, args, callbackContext);
+ } else {
+ download(source, target, args, callbackContext);
+ }
+ return true;
+ } else if (action.equals("abort")) {
+ String objectId = args.getString(0);
+ abort(objectId);
+ callbackContext.success();
+ return true;
+ }
+ return false;
+ }
+
+ private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
+ try {
+ for (Iterator> iter = headers.keys(); iter.hasNext(); ) {
+ /* RFC 2616 says that non-ASCII characters and control
+ * characters are not allowed in header names or values.
+ * Additionally, spaces are not allowed in header names.
+ * RFC 2046 Quoted-printable encoding may be used to encode
+ * arbitrary characters, but we donon- not do that encoding here.
+ */
+ String headerKey = iter.next().toString();
+ String cleanHeaderKey = headerKey.replaceAll("\\n","")
+ .replaceAll("\\s+","")
+ .replaceAll(":", "")
+ .replaceAll("[^\\x20-\\x7E]+", "");
+
+ JSONArray headerValues = headers.optJSONArray(headerKey);
+ if (headerValues == null) {
+ headerValues = new JSONArray();
+
+ /* RFC 2616 also says that any amount of consecutive linear
+ * whitespace within a header value can be replaced with a
+ * single space character, without affecting the meaning of
+ * that value.
+ */
+
+ String headerValue = headers.getString(headerKey);
+ String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n"," ").replaceAll("[^\\x20-\\x7E]+", " ");
+ headerValues.put(finalValue);
+ }
+
+ //Use the clean header key, not the one that we passed in
+ connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0));
+ for (int i = 1; i < headerValues.length(); ++i) {
+ connection.addRequestProperty(headerKey, headerValues.getString(i));
+ }
+ }
+ } catch (JSONException e1) {
+ // No headers to be manipulated!
+ }
+ }
+
+ private String getCookies(final String target) {
+ boolean gotCookie = false;
+ String cookie = null;
+ Class webViewClass = webView.getClass();
+ try {
+ Method gcmMethod = webViewClass.getMethod("getCookieManager");
+ Class iccmClass = gcmMethod.getReturnType();
+ Method gcMethod = iccmClass.getMethod("getCookie", String.class);
+
+ cookie = (String)gcMethod.invoke(
+ iccmClass.cast(
+ gcmMethod.invoke(webView)
+ ), target);
+
+ gotCookie = true;
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ } catch (ClassCastException e) {
+ }
+
+ if (!gotCookie && CookieManager.getInstance() != null) {
+ cookie = CookieManager.getInstance().getCookie(target);
+ }
+
+ return cookie;
+ }
+
+ /**
+ * Uploads the specified file to the server URL provided using an HTTP multipart request.
+ * @param source Full path of the file on the file system
+ * @param target URL of the server to receive the file
+ * @param args JSON Array of args
+ * @param callbackContext callback id for optional progress reports
+ *
+ * args[2] fileKey Name of file request parameter
+ * args[3] fileName File name to be used on server
+ * args[4] mimeType Describes file content type
+ * args[5] params key:value pairs of user-defined parameters
+ * @return FileUploadResult containing result of upload request
+ */
+ private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ Log.d(LOG_TAG, "upload " + source + " to " + target);
+
+ // Setup the options
+ final String fileKey = getArgument(args, 2, "file");
+ final String fileName = getArgument(args, 3, "image.jpg");
+ final String mimeType = getArgument(args, 4, "image/jpeg");
+ final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
+ final boolean trustEveryone = args.optBoolean(6);
+ // Always use chunked mode unless set to false as per API
+ final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
+ // Look for headers on the params map for backwards compatibility with older Cordova versions.
+ final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);
+ final String objectId = args.getString(9);
+ final String httpMethod = getArgument(args, 10, "POST");
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ Log.d(LOG_TAG, "fileKey: " + fileKey);
+ Log.d(LOG_TAG, "fileName: " + fileName);
+ Log.d(LOG_TAG, "mimeType: " + mimeType);
+ Log.d(LOG_TAG, "params: " + params);
+ Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
+ Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
+ Log.d(LOG_TAG, "headers: " + headers);
+ Log.d(LOG_TAG, "objectId: " + objectId);
+ Log.d(LOG_TAG, "httpMethod: " + httpMethod);
+
+ final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
+ // Accept a path or a URI for the source.
+ Uri tmpSrc = Uri.parse(source);
+ final Uri sourceUri = resourceApi.remapUri(
+ tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));
+
+ int uriType = CordovaResourceApi.getUriType(targetUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
+ Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+ HttpURLConnection conn = null;
+ HostnameVerifier oldHostnameVerifier = null;
+ SSLSocketFactory oldSocketFactory = null;
+ int totalBytes = 0;
+ int fixedLength = -1;
+ try {
+ // Create return object
+ FileUploadResult result = new FileUploadResult();
+ FileProgressResult progress = new FileProgressResult();
+
+ //------------------ CLIENT REQUEST
+ // Open a HTTP connection to the URL based on protocol
+ conn = resourceApi.createHttpConnection(targetUri);
+ if (useHttps && trustEveryone) {
+ // Setup the HTTPS connection class to trust everyone
+ HttpsURLConnection https = (HttpsURLConnection)conn;
+ oldSocketFactory = trustAllHosts(https);
+ // Save the current hostnameVerifier
+ oldHostnameVerifier = https.getHostnameVerifier();
+ // Setup the connection not to verify hostnames
+ https.setHostnameVerifier(DO_NOT_VERIFY);
+ }
+
+ // Allow Inputs
+ conn.setDoInput(true);
+
+ // Allow Outputs
+ conn.setDoOutput(true);
+
+ // Don't use a cached copy.
+ conn.setUseCaches(false);
+
+ // Use a post method.
+ conn.setRequestMethod(httpMethod);
+
+ // if we specified a Content-Type header, don't do multipart form upload
+ boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
+ if (multipartFormUpload) {
+ conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
+ }
+
+ // Set the cookies on the response
+ String cookie = getCookies(target);
+
+ if (cookie != null) {
+ conn.setRequestProperty("Cookie", cookie);
+ }
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(conn, headers);
+ }
+
+ /*
+ * Store the non-file portions of the multipart data as a string, so that we can add it
+ * to the contentSize, since it is part of the body of the HTTP request.
+ */
+ StringBuilder beforeData = new StringBuilder();
+ try {
+ for (Iterator> iter = params.keys(); iter.hasNext();) {
+ Object key = iter.next();
+ if(!String.valueOf(key).equals("headers"))
+ {
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"');
+ beforeData.append(LINE_END).append(LINE_END);
+ beforeData.append(params.getString(key.toString()));
+ beforeData.append(LINE_END);
+ }
+ }
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
+ beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
+ beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
+ byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
+ byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");
+
+
+ // Get a input stream of the file on the phone
+ OpenForReadResult readResult = resourceApi.openForRead(sourceUri);
+
+ int stringLength = beforeDataBytes.length + tailParamsBytes.length;
+ if (readResult.length >= 0) {
+ fixedLength = (int)readResult.length;
+ if (multipartFormUpload)
+ fixedLength += stringLength;
+ progress.setLengthComputable(true);
+ progress.setTotal(fixedLength);
+ }
+ Log.d(LOG_TAG, "Content Length: " + fixedLength);
+ // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
+ // http://code.google.com/p/android/issues/detail?id=3164
+ // It also causes OOM if HTTPS is used, even on newer devices.
+ boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
+ useChunkedMode = useChunkedMode || (fixedLength == -1);
+
+ if (useChunkedMode) {
+ conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
+ // Although setChunkedStreamingMode sets this header, setting it explicitly here works
+ // around an OutOfMemoryException when using https.
+ conn.setRequestProperty("Transfer-Encoding", "chunked");
+ } else {
+ conn.setFixedLengthStreamingMode(fixedLength);
+ }
+
+ conn.connect();
+
+ OutputStream sendStream = null;
+ try {
+ sendStream = conn.getOutputStream();
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = conn;
+ }
+
+ if (multipartFormUpload) {
+ //We don't want to change encoding, we just want this to write for all Unicode.
+ sendStream.write(beforeDataBytes);
+ totalBytes += beforeDataBytes.length;
+ }
+
+ // create a buffer of maximum size
+ int bytesAvailable = readResult.inputStream.available();
+ int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ byte[] buffer = new byte[bufferSize];
+
+ // read file and write it into form...
+ int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ long prevBytesRead = 0;
+ while (bytesRead > 0) {
+ result.setBytesSent(totalBytes);
+ sendStream.write(buffer, 0, bytesRead);
+ totalBytes += bytesRead;
+ if (totalBytes > prevBytesRead + 102400) {
+ prevBytesRead = totalBytes;
+ Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
+ }
+ bytesAvailable = readResult.inputStream.available();
+ bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ // Send a progress event.
+ progress.setLoaded(totalBytes);
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+
+ if (multipartFormUpload) {
+ // send multipart form data necessary after file data...
+ sendStream.write(tailParamsBytes);
+ totalBytes += tailParamsBytes.length;
+ }
+ sendStream.flush();
+ } finally {
+ safeClose(readResult.inputStream);
+ safeClose(sendStream);
+ }
+ synchronized (context) {
+ context.connection = null;
+ }
+ Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);
+
+ //------------------ read the SERVER RESPONSE
+ String responseString;
+ int responseCode = conn.getResponseCode();
+ Log.d(LOG_TAG, "response code: " + responseCode);
+ Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
+ TrackingInputStream inStream = null;
+ try {
+ inStream = getInputStream(conn);
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = conn;
+ }
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));
+ byte[] buffer = new byte[1024];
+ int bytesRead = 0;
+ // write bytes to file
+ while ((bytesRead = inStream.read(buffer)) > 0) {
+ out.write(buffer, 0, bytesRead);
+ }
+ responseString = out.toString("UTF-8");
+ } finally {
+ synchronized (context) {
+ context.connection = null;
+ }
+ safeClose(inStream);
+ }
+
+ Log.d(LOG_TAG, "got response from server");
+ Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));
+
+ // send request and retrieve response
+ result.setResponseCode(responseCode);
+ result.setResponse(responseString);
+
+ context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ } catch (Throwable t) {
+ // Shouldn't happen, but will
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t);
+ Log.e(LOG_TAG, error.toString(), t);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (conn != null) {
+ // Revert back to the proper verifier and socket factories
+ // Revert back to the proper verifier and socket factories
+ if (trustEveryone && useHttps) {
+ HttpsURLConnection https = (HttpsURLConnection) conn;
+ https.setHostnameVerifier(oldHostnameVerifier);
+ https.setSSLSocketFactory(oldSocketFactory);
+ }
+ }
+ }
+ }
+ });
+ }
+
+ private static void safeClose(Closeable stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
+ String encoding = conn.getContentEncoding();
+ if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
+ return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
+ }
+ return new SimpleTrackingInputStream(conn.getInputStream());
+ }
+
+ // always verify the host - don't check for certificate
+ private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ };
+ // Create a trust manager that does not validate certificate chains
+ private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return new java.security.cert.X509Certificate[] {};
+ }
+
+ public void checkClientTrusted(X509Certificate[] chain,
+ String authType) throws CertificateException {
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain,
+ String authType) throws CertificateException {
+ }
+ } };
+
+ /**
+ * This function will install a trust manager that will blindly trust all SSL
+ * certificates. The reason this code is being added is to enable developers
+ * to do development using self signed SSL certificates on their web server.
+ *
+ * The standard HttpsURLConnection class will throw an exception on self
+ * signed certificates if this code is not run.
+ */
+ private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
+ // Install the all-trusting trust manager
+ SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
+ try {
+ // Install our all trusting manager
+ SSLContext sc = SSLContext.getInstance("TLS");
+ sc.init(null, trustAllCerts, new java.security.SecureRandom());
+ SSLSocketFactory newFactory = sc.getSocketFactory();
+ connection.setSSLSocketFactory(newFactory);
+ } catch (Exception e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+ return oldFactory;
+ }
+
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection, Throwable throwable) {
+
+ int httpStatus = 0;
+ StringBuilder bodyBuilder = new StringBuilder();
+ String body = null;
+ if (connection != null) {
+ try {
+ if (connection instanceof HttpURLConnection) {
+ httpStatus = ((HttpURLConnection)connection).getResponseCode();
+ InputStream err = ((HttpURLConnection) connection).getErrorStream();
+ if(err != null)
+ {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8"));
+ try {
+ String line = reader.readLine();
+ while(line != null) {
+ bodyBuilder.append(line);
+ line = reader.readLine();
+ if(line != null) {
+ bodyBuilder.append('\n');
+ }
+ }
+ body = bodyBuilder.toString();
+ } finally {
+ reader.close();
+ }
+ }
+ }
+ // IOException can leave connection object in a bad state, so catch all exceptions.
+ } catch (Throwable e) {
+ Log.w(LOG_TAG, "Error getting HTTP status code from connection.", e);
+ }
+ }
+
+ return createFileTransferError(errorCode, source, target, body, httpStatus, throwable);
+ }
+
+ /**
+ * Create an error object based on the passed in errorCode
+ * @param errorCode the error
+ * @return JSONObject containing the error
+ */
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) {
+ JSONObject error = null;
+ try {
+ error = new JSONObject();
+ error.put("code", errorCode);
+ error.put("source", source);
+ error.put("target", target);
+ if(body != null)
+ {
+ error.put("body", body);
+ }
+ if (httpStatus != null) {
+ error.put("http_status", httpStatus);
+ }
+ if (throwable != null) {
+ String msg = throwable.getMessage();
+ if (msg == null || "".equals(msg)) {
+ msg = throwable.toString();
+ }
+ error.put("exception", msg);
+ }
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+ return error;
+ }
+
+ /**
+ * Convenience method to read a parameter from the list of JSON args.
+ * @param args the args passed to the Plugin
+ * @param position the position to retrieve the arg from
+ * @param defaultString the default to be used if the arg does not exist
+ * @return String with the retrieved value
+ */
+ private static String getArgument(JSONArray args, int position, String defaultString) {
+ String arg = defaultString;
+ if (args.length() > position) {
+ arg = args.optString(position);
+ if (arg == null || "null".equals(arg)) {
+ arg = defaultString;
+ }
+ }
+ return arg;
+ }
+
+ /**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ *
+ * @param source URL of the server to receive the file
+ * @param target Full path of the file on the file system
+ */
+ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ Log.d(LOG_TAG, "download " + source + " to " + target);
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ final boolean trustEveryone = args.optBoolean(2);
+ final String objectId = args.getString(3);
+ final JSONObject headers = args.optJSONObject(4);
+
+ final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));
+ // Accept a path or a URI for the source.
+ Uri tmpTarget = Uri.parse(target);
+ final Uri targetUri = resourceApi.remapUri(
+ tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));
+
+ int uriType = CordovaResourceApi.getUriType(sourceUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
+ if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
+ Log.e(LOG_TAG, "Unsupported URI: " + sourceUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
+ * Previously the CordovaWebView class had a method, getWhitelist, which would
+ * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x,
+ * the correct call now is to shouldAllowRequest from the plugin manager.
+ */
+ Boolean shouldAllowRequest = null;
+ if (isLocalTransfer) {
+ shouldAllowRequest = true;
+ }
+ if (shouldAllowRequest == null) {
+ try {
+ Method gwl = webView.getClass().getMethod("getWhitelist");
+ Whitelist whitelist = (Whitelist)gwl.invoke(webView);
+ shouldAllowRequest = whitelist.isUrlWhiteListed(source);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+ if (shouldAllowRequest == null) {
+ try {
+ Method gpm = webView.getClass().getMethod("getPluginManager");
+ PluginManager pm = (PluginManager)gpm.invoke(webView);
+ Method san = pm.getClass().getMethod("shouldAllowRequest", String.class);
+ shouldAllowRequest = (Boolean)san.invoke(pm, source);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+
+ if (!Boolean.TRUE.equals(shouldAllowRequest)) {
+ Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+ HttpURLConnection connection = null;
+ HostnameVerifier oldHostnameVerifier = null;
+ SSLSocketFactory oldSocketFactory = null;
+ File file = null;
+ PluginResult result = null;
+ TrackingInputStream inputStream = null;
+ boolean cached = false;
+
+ OutputStream outputStream = null;
+ try {
+ OpenForReadResult readResult = null;
+
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+
+ Log.d(LOG_TAG, "Download file:" + sourceUri);
+
+ FileProgressResult progress = new FileProgressResult();
+
+ if (isLocalTransfer) {
+ readResult = resourceApi.openForRead(sourceUri);
+ if (readResult.length != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(readResult.length);
+ }
+ inputStream = new SimpleTrackingInputStream(readResult.inputStream);
+ } else {
+ // connect to server
+ // Open a HTTP connection to the URL based on protocol
+ connection = resourceApi.createHttpConnection(sourceUri);
+ if (useHttps && trustEveryone) {
+ // Setup the HTTPS connection class to trust everyone
+ HttpsURLConnection https = (HttpsURLConnection)connection;
+ oldSocketFactory = trustAllHosts(https);
+ // Save the current hostnameVerifier
+ oldHostnameVerifier = https.getHostnameVerifier();
+ // Setup the connection not to verify hostnames
+ https.setHostnameVerifier(DO_NOT_VERIFY);
+ }
+
+ connection.setRequestMethod("GET");
+
+ // TODO: Make OkHttp use this CookieManager by default.
+ String cookie = getCookies(sourceUri.toString());
+
+ if(cookie != null)
+ {
+ connection.setRequestProperty("cookie", cookie);
+ }
+
+ // This must be explicitly set for gzip progress tracking to work.
+ connection.setRequestProperty("Accept-Encoding", "gzip");
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(connection, headers);
+ }
+
+ connection.connect();
+ if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ cached = true;
+ connection.disconnect();
+ Log.d(LOG_TAG, "Resource not modified: " + source);
+ JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null);
+ result = new PluginResult(PluginResult.Status.ERROR, error);
+ } else {
+ if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
+ // Only trust content-length header if we understand
+ // the encoding -- identity or gzip
+ if (connection.getContentLength() != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(connection.getContentLength());
+ }
+ }
+ inputStream = getInputStream(connection);
+ }
+ }
+
+ if (!cached) {
+ try {
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = connection;
+ }
+
+ // write bytes to file
+ byte[] buffer = new byte[MAX_BUFFER_SIZE];
+ int bytesRead = 0;
+ outputStream = resourceApi.openOutputStream(targetUri);
+ while ((bytesRead = inputStream.read(buffer)) > 0) {
+ outputStream.write(buffer, 0, bytesRead);
+ // Send a progress event.
+ progress.setLoaded(inputStream.getTotalRawBytesRead());
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+ } finally {
+ synchronized (context) {
+ context.connection = null;
+ }
+ safeClose(inputStream);
+ safeClose(outputStream);
+ }
+
+ Log.d(LOG_TAG, "Saved file: " + target);
+
+
+ // create FileEntry object
+ Class webViewClass = webView.getClass();
+ PluginManager pm = null;
+ try {
+ Method gpm = webViewClass.getMethod("getPluginManager");
+ pm = (PluginManager) gpm.invoke(webView);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ if (pm == null) {
+ try {
+ Field pmf = webViewClass.getField("pluginManager");
+ pm = (PluginManager)pmf.get(webView);
+ } catch (NoSuchFieldException e) {
+ } catch (IllegalAccessException e) {
+ }
+ }
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+ FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
+ if (filePlugin != null) {
+ JSONObject fileEntry = filePlugin.getEntryForFile(file);
+ if (fileEntry != null) {
+ result = new PluginResult(PluginResult.Status.OK, fileEntry);
+ } else {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null);
+ Log.e(LOG_TAG, "File plugin cannot represent download path");
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ }
+ } else {
+ Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file");
+ result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file");
+ }
+ }
+
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
+ } catch (Throwable e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (connection != null) {
+ // Revert back to the proper verifier and socket factories
+ if (trustEveryone && useHttps) {
+ HttpsURLConnection https = (HttpsURLConnection) connection;
+ https.setHostnameVerifier(oldHostnameVerifier);
+ https.setSSLSocketFactory(oldSocketFactory);
+ }
+ }
+
+ if (result == null) {
+ result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null));
+ }
+ // Remove incomplete download.
+ if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
+ file.delete();
+ }
+ context.sendPluginResult(result);
+ }
+ }
+ });
+ }
+
+ /**
+ * Abort an ongoing upload or download.
+ */
+ private void abort(String objectId) {
+ final RequestContext context;
+ synchronized (activeRequests) {
+ context = activeRequests.remove(objectId);
+ }
+ if (context != null) {
+ // Closing the streams can block, so execute on a background thread.
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ synchronized (context) {
+ File file = context.targetFile;
+ if (file != null) {
+ file.delete();
+ }
+ // Trigger the abort callback immediately to minimize latency between it and abort() being called.
+ JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
+ context.aborted = true;
+ if (context.connection != null) {
+ try {
+ context.connection.disconnect();
+ } catch (Exception e) {
+ Log.e(LOG_TAG, "CB-8431 Catch workaround for fatal exception", e);
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/platforms/android/src/org/apache/cordova/filetransfer/FileUploadResult.java b/platforms/android/src/org/apache/cordova/filetransfer/FileUploadResult.java
new file mode 100644
index 0000000..c24ea78
--- /dev/null
+++ b/platforms/android/src/org/apache/cordova/filetransfer/FileUploadResult.java
@@ -0,0 +1,73 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Encapsulates the result and/or status of uploading a file to a remote server.
+ */
+public class FileUploadResult {
+
+ private long bytesSent = 0; // bytes sent
+ private int responseCode = -1; // HTTP response code
+ private String response = null; // HTTP response
+ private String objectId = null; // FileTransfer object id
+
+ public long getBytesSent() {
+ return bytesSent;
+ }
+
+ public void setBytesSent(long bytes) {
+ this.bytesSent = bytes;
+ }
+
+ public int getResponseCode() {
+ return responseCode;
+ }
+
+ public void setResponseCode(int responseCode) {
+ this.responseCode = responseCode;
+ }
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public String getObjectId() {
+ return objectId;
+ }
+
+ public void setObjectId(String objectId) {
+ this.objectId = objectId;
+ }
+
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{bytesSent:" + bytesSent +
+ ",responseCode:" + responseCode +
+ ",response:" + JSONObject.quote(response) +
+ ",objectId:" + JSONObject.quote(objectId) + "}");
+ }
+}
diff --git a/plugins/android.json b/plugins/android.json
index 0bfe65f..70c0b28 100644
--- a/plugins/android.json
+++ b/plugins/android.json
@@ -31,6 +31,12 @@
},
"cordova-plugin-inappbrowser": {
"PACKAGE_NAME": "com.raataar.wolle_rosen_kaufen"
+ },
+ "cordova-plugin-file": {
+ "PACKAGE_NAME": "com.raataar.wolle_rosen_kaufen"
+ },
+ "cordova-plugin-file-transfer": {
+ "PACKAGE_NAME": "com.raataar.wolle_rosen_kaufen"
}
},
"dependent_plugins": {}
diff --git a/plugins/cordova-plugin-file-transfer/CONTRIBUTING.md b/plugins/cordova-plugin-file-transfer/CONTRIBUTING.md
new file mode 100644
index 0000000..4c8e6a5
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/CONTRIBUTING.md
@@ -0,0 +1,37 @@
+
+
+# Contributing to Apache Cordova
+
+Anyone can contribute to Cordova. And we need your contributions.
+
+There are multiple ways to contribute: report bugs, improve the docs, and
+contribute code.
+
+For instructions on this, start with the
+[contribution overview](http://cordova.apache.org/contribute/).
+
+The details are explained there, but the important items are:
+ - Sign and submit an Apache ICLA (Contributor License Agreement).
+ - Have a Jira issue open that corresponds to your contribution.
+ - Run the tests so your patch doesn't break existing functionality.
+
+We look forward to your contributions!
diff --git a/plugins/cordova-plugin-file-transfer/LICENSE b/plugins/cordova-plugin-file-transfer/LICENSE
new file mode 100644
index 0000000..7a4a3ea
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed 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.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file-transfer/NOTICE b/plugins/cordova-plugin-file-transfer/NOTICE
new file mode 100644
index 0000000..46fed23
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/NOTICE
@@ -0,0 +1,8 @@
+Apache Cordova
+Copyright 2012 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+
+This product includes a copy of OkHttp from:
+https://github.com/square/okhttp
diff --git a/plugins/cordova-plugin-file-transfer/README.md b/plugins/cordova-plugin-file-transfer/README.md
new file mode 100644
index 0000000..76df55e
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/README.md
@@ -0,0 +1,310 @@
+
+
+# cordova-plugin-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);
+ }
+
+:warning: 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%20Transfer%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
+
+## 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 or PUT 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. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used. (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`.
+
+### Browser Quirks
+
+- __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest
+
+## 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.
+
+### Browser Quirks
+
+- __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest
+
+## 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//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/plugins/cordova-plugin-file-transfer/RELEASENOTES.md b/plugins/cordova-plugin-file-transfer/RELEASENOTES.md
new file mode 100644
index 0000000..10c7022
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/RELEASENOTES.md
@@ -0,0 +1,240 @@
+
+# Release Notes
+
+### 1.4.0 (Nov 18, 2015)
+* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
+* [CB-9879](https://issues.apache.org/jira/browse/CB-9879) `getCookie`s can cause unhandled `NullPointerException`
+* [CB-6928](https://issues.apache.org/jira/browse/CB-6928) Wrong behaviour transferring cacheable content
+* [CB-51](https://issues.apache.org/jira/browse/CB-51) FileTransfer - Support `PUT` Method
+* [CB-9906](https://issues.apache.org/jira/browse/CB-9906) cleanup duplicate code, removed 2nd `isWP8` declaration.
+* [CB-9950](https://issues.apache.org/jira/browse/CB-9950) Unpend Filetransfer spec.27 on **wp8** as custom headers are now supported
+* [CB-9843](https://issues.apache.org/jira/browse/CB-9843) Added **wp8** quirk to test spec 12
+* Fixing contribute link.
+* [CB-8431](https://issues.apache.org/jira/browse/CB-8431) File Transfer tests crash on **Android Lolipop**
+* [CB-9790](https://issues.apache.org/jira/browse/CB-9790) Align `FileUploadOptions` `fileName` and `mimeType` default parameter values to the docs on **iOS**
+* [CB-9385](https://issues.apache.org/jira/browse/CB-9385) Return `FILE_NOT_FOUND_ERR` when receiving `404` code on **iOS**
+* [CB-9791](https://issues.apache.org/jira/browse/CB-9791) Decreased download and upload tests timeout
+
+### 1.3.0 (Sep 18, 2015)
+* Found issue where : is accepted as a valid header, this is obviously wrong
+* [CB-9562](https://issues.apache.org/jira/browse/CB-9562) Fixed incorrect headers handling on Android
+* Fixing headers so they don't accept non-ASCII
+* updated tests to use cordova apache vm
+* [CB-9493](https://issues.apache.org/jira/browse/CB-9493) Fix file paths in file-transfer manual tests
+* [CB-8816](https://issues.apache.org/jira/browse/CB-8816) Add cdvfile:// support on windows
+* [CB-9376](https://issues.apache.org/jira/browse/CB-9376) Fix FileTransfer plugin manual tests issue - 'undefined' in paths
+
+### 1.2.1 (Jul 7, 2015)
+* [CB-9275](https://issues.apache.org/jira/browse/CB-9275) [WP8] Fix build failure on WP8 by using reflection to detect presence of JSON.NET based serialization
+* Updated code per code review.
+* Updated documentation for browser
+* Added option to allow for passing cookies automatically in the browser
+
+### 1.2.0 (Jun 17, 2015)
+* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer
+* [CB-6503](https://issues.apache.org/jira/browse/CB-6503): Null pointer check for headers in upload (This closes #27)
+* [CB-6503](https://issues.apache.org/jira/browse/CB-6503): Allow payload content-types other than multipart/form-data to be used for upload
+* Fix NoSuchMethodException looking up cookies.
+* fix npm md issue
+* [CB-8951](https://issues.apache.org/jira/browse/CB-8951) (wp8) Handle exceptions in download() and upload() again
+* [wp8] Relaxed engine version requirement, using reflection to see if methods are available
+* Check for the existence of Json.net assembly to determin how we deserialize our headers.
+* relax engine requirement to allow -dev versions
+* Remove verbose console log messages
+* fix bad commit (mine) for cordova-wp8@4.0.0 engine req
+* bump required cordova-wp8 version to 4.0.0
+* This closes #80, This closes #12
+* fix failing test resulting from overlapping async calls
+* [CB-8721](https://issues.apache.org/jira/browse/CB-8721) Fixes incorrect headers and upload params parsing on wp8
+* Replace all slashes in windows path
+
+### 1.1.0 (May 06, 2015)
+* [CB-8951](https://issues.apache.org/jira/browse/CB-8951) Fixed crash related to headers parsing on **wp8**
+* [CB-8933](https://issues.apache.org/jira/browse/CB-8933) Increased download and upload test timeout
+* [CB-6313](https://issues.apache.org/jira/browse/CB-6313) **wp8**: Extra boundary in upload
+* [CB-8761](https://issues.apache.org/jira/browse/CB-8761) **wp8**: Copy cookies from WebBrowser
+
+### 1.0.0 (Apr 15, 2015)
+* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) bumped version of file dependency
+* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump
+* [CB-8641](https://issues.apache.org/jira/browse/CB-8641) Fixed tests to pass on windows and wp8
+* [CB-8583](https://issues.apache.org/jira/browse/CB-8583) Forces download to overwrite existing target file
+* [CB-8589](https://issues.apache.org/jira/browse/CB-8589) Fixes upload failure when server's response doesn't contain any data
+* [CB-8747](https://issues.apache.org/jira/browse/CB-8747) updated dependency, added peer dependency
+* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name
+* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id
+* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id
+* Use TRAVIS_BUILD_DIR, install paramedic by npm
+* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme
+* [CB-8654](https://issues.apache.org/jira/browse/CB-8654) Note WP8 download requests caching in docs
+* [CB-8590](https://issues.apache.org/jira/browse/CB-8590) (Windows) Fixed download.onprogress.lengthComputable
+* [CB-8566](https://issues.apache.org/jira/browse/CB-8566) Integrate TravisCI
+* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer
+* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
+* [CB-8495](https://issues.apache.org/jira/browse/CB-8495) Fixed wp8 and wp81 test failures
+* [CB-7957](https://issues.apache.org/jira/browse/CB-7957) Adds support for `browser` platform
+* [CB-8429](https://issues.apache.org/jira/browse/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](https://issues.apache.org/jira/browse/CB-8407) Use File proxy to construct valid FileEntry for download success callback
+* [CB-8407](https://issues.apache.org/jira/browse/CB-8407) Removes excess path to native path conversion in download method
+* [CB-8429](https://issues.apache.org/jira/browse/CB-8429) Updated version and RELEASENOTES.md for release 0.5.0
+* [CB-7957](https://issues.apache.org/jira/browse/CB-7957) Adds support for `browser` platform
+* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) Fixes JSHint and formatting issues
+* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) Updates tests and documentation
+* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) Rewrite upload method to support progress events properly
+* android: Fix error reporting for unknown uri type on sourceUri instead of targetUri
+
+### 0.5.0 (Feb 04, 2015)
+* [CB-8407](https://issues.apache.org/jira/browse/CB-8407) windows: Fix download of `ms-appdata:///` URIs
+* [CB-8095](https://issues.apache.org/jira/browse/CB-8095) windows: Rewrite upload method to support progress events properly
+* [CB-5059](https://issues.apache.org/jira/browse/CB-5059) android: Add a CookieManager abstraction for pluggable webviews
+* ios: Fix compile warning about implicity int conversion
+* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use argumentForIndex rather than NSArray extension
+* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) ios: Use a local copy of DLog macro rather than CordovaLib version
+* [CB-8296](https://issues.apache.org/jira/browse/CB-8296) ios: Fix crash when upload fails and file is not yet created (close #57)
+* Document "body" property on FileTransferError
+* [CB-7912](https://issues.apache.org/jira/browse/CB-7912) ios, android: Update to work with whitelist plugins in Cordova 4.x
+* 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](https://issues.apache.org/jira/browse/CB-8093) Fixes incorrect FileTransferError returned in case of download failure
+
+### 0.4.8 (Dec 02, 2014)
+* [CB-8021](https://issues.apache.org/jira/browse/CB-8021) - adds documentation for `httpMethod` to `doc/index.md`. However, translations still need to be addressed.
+* [CB-7223](https://issues.apache.org/jira/browse/CB-7223) spec.27 marked pending for **wp8**
+* [CB-6900](https://issues.apache.org/jira/browse/CB-6900) fixed `spec.7` for **wp8**
+* [CB-7944](https://issues.apache.org/jira/browse/CB-7944) Pended unsupported auto tests for *Windows*
+* [CB-7977](https://issues.apache.org/jira/browse/CB-7977) Mention `deviceready` in plugin docs
+* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-file-transfer documentation translation: cordova-plugin-file-transfer
+
+### 0.4.7 (Oct 03, 2014)
+* Construct proper FileEntry with nativeURL property set
+* [CB-7532](https://issues.apache.org/jira/browse/CB-7532) Handle non-existent download dirs properly
+* [CB-7529](https://issues.apache.org/jira/browse/CB-7529) Adds support for 'ms-appdata' URIs for windows
+
+### 0.4.6 (Sep 17, 2014)
+* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-file-transfer documentation translation
+* [CB-7249](https://issues.apache.org/jira/browse/CB-7249) cordova-plugin-file-transfer documentation translation
+* [CB-7423](https://issues.apache.org/jira/browse/CB-7423) fix spec28,29 lastProgressEvent not visible to afterEach function
+* Amazon related changes.
+* Remove dupe file windows+windows8 both use the same one
+* [CB-7316](https://issues.apache.org/jira/browse/CB-7316) Updates docs with actual information.
+* [CB-7316](https://issues.apache.org/jira/browse/CB-7316) Adds support for Windows platform, moves \*Proxy files to proper directory.
+* [CB-7316](https://issues.apache.org/jira/browse/CB-7316) Improves current specs compatibility:
+* added documentation for new test
+* [CB-6466](https://issues.apache.org/jira/browse/CB-6466) Fix failing test due to recent url change
+* [CB-6466](https://issues.apache.org/jira/browse/CB-6466) created mobile-spec test
+* Renamed test dir, added nested plugin.xml and test
+* Fixed failing spec.19 on wp8
+* added documentation to manual tests
+* [CB-6961](https://issues.apache.org/jira/browse/CB-6961) port file-transfer tests to framework
+
+### 0.4.5 (Aug 06, 2014)
+* Upload parameters out of order
+* **FirefoxOS** initial implementation
+* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): Expose FileTransferError.exception to application
+* [CB-6928](https://issues.apache.org/jira/browse/CB-6928): Add new error code to documentation
+* [CB-6928](https://issues.apache.org/jira/browse/CB-6928): Handle 304 status code
+* [CB-6928](https://issues.apache.org/jira/browse/CB-6928): Open output stream only if it's necessary.
+* [BlackBerry10] Minor doc correction
+* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs
+* [Windows8] upload uses the provided fileName or the actual fileName
+* [CB-2420](https://issues.apache.org/jira/browse/CB-2420) [Windows8] honor fileKey and param options. This closes #15
+* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): Update new docs to match AlexNennker's changes in PR30
+* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): Continue previous commit with one new instance (This closes #30)
+* [CB-6781](https://issues.apache.org/jira/browse/CB-6781): add the exception text to the error object
+* [CB-6890](https://issues.apache.org/jira/browse/CB-6890): Fix pluginManager access for 4.0.x branch
+
+### 0.4.4 (Jun 05, 2014)
+* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #21
+* ubuntu: support 'cdvfile' URI
+* [CB-6802](https://issues.apache.org/jira/browse/CB-6802) Add license
+* Upload progress now works also for second file
+* [CB-6706](https://issues.apache.org/jira/browse/CB-6706): Relax dependency on file plugin
+* [CB-3440](https://issues.apache.org/jira/browse/CB-3440) [BlackBerry10] Update implementation to use modules from file plugin
+* [CB-6378](https://issues.apache.org/jira/browse/CB-6378) Use connection.disconnect() instead of stream.close() for thread-safety
+* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
+* [CB-6466](https://issues.apache.org/jira/browse/CB-6466) Auto-create directories in download
+* [CB-6494](https://issues.apache.org/jira/browse/CB-6494) android: Fix upload of KitKat content URIs
+* Upleveled from android port with following commits: 3c1ff16 Andrew Grieve - [CB-5762](https://issues.apache.org/jira/browse/CB-5762) android: Fix lengthComputable set wrong for gzip downloads 8374b3d Colin Mahoney - [CB-5631](https://issues.apache.org/jira/browse/CB-5631) Removed SimpleTrackingInputStream.read(byte[] buffer) 6f91ac3 Bas Bosman - [CB-4907](https://issues.apache.org/jira/browse/CB-4907) Close stream when we're finished with it 651460f Christoph Neumann - [CB-6000](https://issues.apache.org/jira/browse/CB-6000) Nginx rejects Content-Type without a space before "boundary". 35f80e4 Ian Clelland - [CB-6050](https://issues.apache.org/jira/browse/CB-6050): Use instance method on actual file plugin object to get FileEntry to return on download
+* [CB-5980](https://issues.apache.org/jira/browse/CB-5980) Updated version and RELEASENOTES.md for release 0.4.1
+
+### 0.4.3 (Apr 17, 2014)
+* [CB-6422](https://issues.apache.org/jira/browse/CB-6422) [windows8] use cordova/exec/proxy
+* iOS: Fix error where files were not removed on abort
+* [CB-5175](https://issues.apache.org/jira/browse/CB-5175): [ios] CDVFileTransfer asynchronous download (Fixes #24)
+* [ios] Cast id references to NSURL to avoid compiler warnings (Fixes: apache/cordova-plugin-file-transfer#18)
+* [CB-6212](https://issues.apache.org/jira/browse/CB-6212): [iOS] fix warnings compiled under arm64 64-bit
+* [CB-5762](https://issues.apache.org/jira/browse/CB-5762): [FireOS] android: Fix lengthComputable set wrong for gzip downloads
+* [CB-5631](https://issues.apache.org/jira/browse/CB-5631): [FireOS] Removed SimpleTrackingInputStream.read(byte[] buffer)
+* [CB-4907](https://issues.apache.org/jira/browse/CB-4907): [FireOS] Close stream when we're finished with it
+* [CB-6000](https://issues.apache.org/jira/browse/CB-6000): [FireOS] Nginx rejects Content-Type without a space before "boundary".
+* [CB-6050](https://issues.apache.org/jira/browse/CB-6050): [FireOS] Use instance method on actual file plugin object to get FileEntry to return on download
+* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers
+
+### 0.4.2 (Feb 28, 2014)
+* [CB-6106](https://issues.apache.org/jira/browse/CB-6106) Ensure that nativeURL is used by file transfer download
+* iOS: Fix default value for trustAllHosts on iOS (YES->NO)
+* [CB-6059](https://issues.apache.org/jira/browse/CB-6059) iOS: Stop FileTransfer.download doing IO on the UI thread.
+* [CB-5588](https://issues.apache.org/jira/browse/CB-5588) iOS: Add response headers to upload result
+* [CB-2190](https://issues.apache.org/jira/browse/CB-2190) iOS: Make backgroundTaskId apply to downloads as well. Move backgroundTaskId to the delegate.
+* [CB-6050](https://issues.apache.org/jira/browse/CB-6050) Android: Use instance method on actual file plugin object to get FileEntry to return on download
+* [CB-6000](https://issues.apache.org/jira/browse/CB-6000) Android: Nginx rejects Content-Type without a space before "boundary".
+* [CB-4907](https://issues.apache.org/jira/browse/CB-4907) Android: Close stream when we're finished with it
+* [CB-6022](https://issues.apache.org/jira/browse/CB-6022) Add backwards-compatibility notes to doc
+
+### 0.4.1 (Feb 05, 2014)
+* [CB-5365](https://issues.apache.org/jira/browse/CB-5365) Remove unused exception var to prevent warnings?
+* [CB-2421](https://issues.apache.org/jira/browse/CB-2421) explicitly write the bytesSent,responseCode,result to the FileUploadResult pending release of cordova-plugin-file dependency, added some sanity checks for callbacks
+* iOS: Update for new file plugin api
+* [CB-5631](https://issues.apache.org/jira/browse/CB-5631) Removed SimpleTrackingInputStream.read(byte[] buffer)
+* [CB-5762](https://issues.apache.org/jira/browse/CB-5762) android: Fix lengthComputable set wrong for gzip downloads
+* [CB-4899](https://issues.apache.org/jira/browse/CB-4899) [BlackBerry10] Improve binary file transfer download
+* Delete stale test/ directory
+* [CB-5722](https://issues.apache.org/jira/browse/CB-5722) [BlackBerry10] Update upload function to use native file object
+* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Delete stale snapshot of plugin docs
+* Remove @1 designation from file plugin dependency until pushed to npm
+* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Update to work with filesystem URLs
+
+### 0.4.0 (Dec 4, 2013)
+* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Partial revert; we're not ready yet for FS urls
+* add ubuntu platform
+* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Minor version bump
+* [CB-5466](https://issues.apache.org/jira/browse/CB-5466): Update FileTransfer plugin to accept filesystem urls
+* Added amazon-fireos platform. Change to use amazon-fireos as the platform if the user agen string contains 'cordova-amazon-fireos'
+
+### 0.3.4 (Oct 28, 2013)
+* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag to plugin.xml for file transfer plugin
+* [CB-5010](https://issues.apache.org/jira/browse/CB-5010) Incremented plugin version on dev branch.
+
+### 0.3.3 (Oct 9, 2013)
+* removed un-needed undef check
+* Fix missing headers in Windows 8 upload proxy
+* Fix missing headers in Windows 8 Proxy
+* Fix Windows 8 HTMLAnchorElement return host:80 which force Basic Auth Header to replace options Auth Header
+* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch.
+
+### 0.3.2 (Sept 25, 2013)
+* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version
+* [windows8] commandProxy was moved
+* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) updating core references
+* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.file-transfer to org.apache.cordova.file-transfer and updating dependency
+* Rename CHANGELOG.md -> RELEASENOTES.md
diff --git a/plugins/cordova-plugin-file-transfer/doc/de/README.md b/plugins/cordova-plugin-file-transfer/doc/de/README.md
new file mode 100644
index 0000000..03191cb
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/de/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+Plugin-Dokumentation:
+
+Dieses Plugin ermöglicht Ihnen zum Hochladen und Herunterladen von Dateien.
+
+Dieses Plugin wird global `FileTransfer`, `FileUploadOptions` Konstruktoren definiert.
+
+Obwohl im globalen Gültigkeitsbereich, sind sie nicht bis nach dem `deviceready`-Ereignis.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Installation
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Unterstützte Plattformen
+
+ * Amazon Fire OS
+ * Android
+ * BlackBerry 10
+ * Browser
+ * Firefox OS **
+ * iOS
+ * Windows Phone 7 und 8 *
+ * Windows 8
+ * Windows
+
+\ * *Unterstützen keine `Onprogress` noch `abort()` *
+
+\ ** * `Onprogress` nicht unterstützt*
+
+# FileTransfer
+
+Das `FileTransfer` -Objekt stellt eine Möglichkeit zum Hochladen von Dateien, die mithilfe einer HTTP-mehrteiligen POST oder PUT-Anforderung, und auch Dateien herunterladen.
+
+## Eigenschaften
+
+ * **OnProgress**: aufgerufen, wobei ein `ProgressEvent` wann wird eine neue Datenmenge übertragen. *(Funktion)*
+
+## Methoden
+
+ * **Upload**: sendet eine Datei an einen Server.
+
+ * **Download**: lädt eine Datei vom Server.
+
+ * **abort**: Abbruch eine Übertragung in Bearbeitung.
+
+## Upload
+
+**Parameter**:
+
+ * **FileURL**: Dateisystem-URL, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten)
+
+ * **Server**: URL des Servers, die Datei zu empfangen, wie kodiert`encodeURI()`.
+
+ * **successCallback**: ein Rückruf, der ein `FileUploadResult`-Objekt übergeben wird. *(Funktion)*
+
+ * **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileUploadResult`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)*
+
+ * **Optionen**: optionale Parameter *(Objekt)*. Gültige Schlüssel:
+
+ * **FileKey**: der Name des Form-Elements. Wird standardmäßig auf `file` . (DOM-String und enthält)
+ * **Dateiname**: der Dateiname beim Speichern der Datei auf dem Server verwendet. Wird standardmäßig auf `image.jpg` . (DOM-String und enthält)
+ * **httpMethod**: die HTTP-Methode, die-entweder `PUT` oder `POST`. Der Standardwert ist `POST`. (DOM-String und enthält)
+ * **mimeType**: den Mime-Typ der Daten hochzuladen. Standardwerte auf `Image/Jpeg`. (DOM-String und enthält)
+ * **params**: eine Reihe von optionalen Schlüssel/Wert-Paaren in der HTTP-Anforderung übergeben. (Objekt)
+ * **chunkedMode**: ob die Daten in "Chunked" streaming-Modus hochladen. Der Standardwert ist `true`. (Boolean)
+ * **headers**: eine Karte von Header-Name-Header-Werte. Verwenden Sie ein Array, um mehr als einen Wert anzugeben. Auf iOS, FireOS und Android wenn ein Content-Type-Header vorhanden ist, werden mehrteilige Formulardaten nicht verwendet werden. (Object)
+ * **httpMethod**: die HTTP-Methode zu verwenden, z.B. POST oder PUT. Der Standardwert ist `POST`. (DOM-String enthält)
+
+ * **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)*
+
+### Beispiel
+
+ // !! 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);
+
+
+### Beispiel mit hochladen Kopf- und Progress-Ereignisse (Android und iOS nur)
+
+ 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
+
+Ein `FileUploadResult`-Objekt wird an den Erfolg-Rückruf des `Objekts FileTransfer`-Upload()-Methode übergeben.
+
+### Eigenschaften
+
+ * **BytesSent**: die Anzahl der Bytes, die als Teil des Uploads an den Server gesendet. (lange)
+
+ * **ResponseCode**: die HTTP-Response-Code vom Server zurückgegeben. (lange)
+
+ * **response**: der HTTP-Antwort vom Server zurückgegeben. (DOM-String und enthält)
+
+ * **Header**: die HTTP-Response-Header vom Server. (Objekt)
+
+ * Derzeit unterstützt auf iOS nur.
+
+### iOS Macken
+
+ * Unterstützt keine `responseCode` oder`bytesSent`.
+
+## Download
+
+**Parameter**:
+
+ * **source**: URL des Servers, um die Datei herunterzuladen, wie kodiert`encodeURI()`.
+
+ * **target**: Dateisystem-Url, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten)
+
+ * **SuccessCallback**: ein Rückruf, der übergeben wird ein `FileEntry` Objekt. *(Funktion)*
+
+ * **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileEntry`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)*
+
+ * **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)*
+
+ * **Options**: optionale Parameter, derzeit nur unterstützt Kopfzeilen (z. B. Autorisierung (Standardauthentifizierung), etc.).
+
+### Beispiel
+
+ // !! 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 Macken
+
+ * Downloaden anfordert, wird von native Implementierung zwischengespeichert wird. Um zu vermeiden, Zwischenspeicherung, übergeben `If-Modified-Since` Header Methode herunterladen.
+
+## abort
+
+Bricht einen in-Progress-Transfer. Der Onerror-Rückruf wird ein FileTransferError-Objekt übergeben, die einen Fehlercode FileTransferError.ABORT_ERR hat.
+
+### Beispiel
+
+ // !! 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
+
+Ein `FileTransferError`-Objekt wird an eine Fehler-Callback übergeben, wenn ein Fehler auftritt.
+
+### Eigenschaften
+
+ * **Code**: einer der vordefinierten Fehlercodes aufgeführt. (Anzahl)
+
+ * **Quelle**: URL der Quelle. (String)
+
+ * **Ziel**: URL zum Ziel. (String)
+
+ * **HTTP_STATUS**: HTTP-Statuscode. Dieses Attribut ist nur verfügbar, wenn ein Response-Code aus der HTTP-Verbindung eingeht. (Anzahl)
+
+ * **body** Antworttext. Dieses Attribut ist nur verfügbar, wenn eine Antwort von der HTTP-Verbindung eingeht. (String)
+
+ * **exception**: entweder e.getMessage oder e.toString (String)
+
+### Konstanten
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Hinweise rückwärts Kompatibilität
+
+Frühere Versionen des Plugins würde nur Gerät-Absolute-Dateipfade als Quelle für Uploads oder als Ziel für Downloads übernehmen. Diese Pfade wäre in der Regel der form
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Für rückwärts Kompatibilität, diese Pfade noch akzeptiert werden, und wenn Ihre Anwendung Pfade wie diese im permanenten Speicher aufgezeichnet hat, dann sie können weiter verwendet werden.
+
+Diese Pfade waren zuvor in der Eigenschaft `fullPath` `FileEntry` und `DirectoryEntry`-Objekte, die durch das Plugin Datei zurückgegeben ausgesetzt. Neue Versionen der die Datei-Erweiterung, jedoch nicht länger werden diese Pfade zu JavaScript.
+
+Wenn Sie ein auf eine neue Upgrade (1.0.0 oder neuere) Version der Datei, und Sie haben zuvor mit `entry.fullPath` als Argumente `download()` oder `upload()`, dann ändern Sie den Code, um die Dateisystem-URLs verwenden müssen.
+
+`FileEntry.toURL()` und `DirectoryEntry.toURL()` zurück, eine Dateisystem-URL in der form
+
+ 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
diff --git a/plugins/cordova-plugin-file-transfer/doc/de/index.md b/plugins/cordova-plugin-file-transfer/doc/de/index.md
new file mode 100644
index 0000000..4081503
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/de/index.md
@@ -0,0 +1,302 @@
+
+
+# cordova-plugin-file-transfer
+
+Dieses Plugin ermöglicht Ihnen zum Hochladen und Herunterladen von Dateien.
+
+Dieses Plugin wird global `FileTransfer`, `FileUploadOptions` Konstruktoren definiert.
+
+Obwohl im globalen Gültigkeitsbereich, sind sie nicht bis nach dem `deviceready`-Ereignis.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Installation
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Unterstützte Plattformen
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Browser
+* Firefox OS **
+* iOS
+* Windows Phone 7 und 8 *
+* Windows 8
+* Windows
+
+* *Unterstützen keine `onprogress` noch `abort()`*
+
+* * *`onprogress` nicht unterstützt*
+
+# FileTransfer
+
+Das `FileTransfer`-Objekt bietet eine Möglichkeit zum Hochladen von Dateien, die mithilfe einer HTTP-Anforderung für mehrteiligen POST sowie Informationen zum Herunterladen von Dateien sowie.
+
+## Eigenschaften
+
+* **OnProgress**: aufgerufen, wobei ein `ProgressEvent` wann wird eine neue Datenmenge übertragen. *(Funktion)*
+
+## Methoden
+
+* **Upload**: sendet eine Datei an einen Server.
+
+* **Download**: lädt eine Datei vom Server.
+
+* **abort**: Abbruch eine Übertragung in Bearbeitung.
+
+## Upload
+
+**Parameter**:
+
+* **FileURL**: Dateisystem-URL, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten)
+
+* **Server**: URL des Servers, die Datei zu empfangen, wie kodiert`encodeURI()`.
+
+* **successCallback**: ein Rückruf, der ein `FileUploadResult`-Objekt übergeben wird. *(Funktion)*
+
+* **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileUploadResult`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)*
+
+* **Optionen**: optionale Parameter *(Objekt)*. Gültige Schlüssel:
+
+ * **FileKey**: der Name des Form-Elements. Wird standardmäßig auf `file` . (DOM-String und enthält)
+ * **Dateiname**: der Dateiname beim Speichern der Datei auf dem Server verwendet. Wird standardmäßig auf `image.jpg` . (DOM-String und enthält)
+ * **httpMethod**: die HTTP-Methode, die-entweder `PUT` oder `POST`. Der Standardwert ist `POST`. (DOM-String und enthält)
+ * **mimeType**: den Mime-Typ der Daten hochzuladen. Standardwerte auf `Image/Jpeg`. (DOM-String und enthält)
+ * **params**: eine Reihe von optionalen Schlüssel/Wert-Paaren in der HTTP-Anforderung übergeben. (Objekt)
+ * **chunkedMode**: ob die Daten in "Chunked" streaming-Modus hochladen. Der Standardwert ist `true`. (Boolean)
+ * **headers**: eine Karte von Header-Name-Header-Werte. Verwenden Sie ein Array, um mehr als einen Wert anzugeben. (Objekt)
+
+* **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)*
+
+### Beispiel
+
+ // !! 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);
+
+
+### Beispiel mit hochladen Kopf- und Progress-Ereignisse (Android und iOS nur)
+
+ 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
+
+Ein `FileUploadResult`-Objekt wird an den Erfolg-Rückruf des `Objekts FileTransfer`-Upload()-Methode übergeben.
+
+### Eigenschaften
+
+* **BytesSent**: die Anzahl der Bytes, die als Teil des Uploads an den Server gesendet. (lange)
+
+* **ResponseCode**: die HTTP-Response-Code vom Server zurückgegeben. (lange)
+
+* **response**: der HTTP-Antwort vom Server zurückgegeben. (DOM-String und enthält)
+
+* **Header**: die HTTP-Response-Header vom Server. (Objekt)
+
+ * Derzeit unterstützt auf iOS nur.
+
+### iOS Macken
+
+* Unterstützt keine `responseCode` oder`bytesSent`.
+
+## Download
+
+**Parameter**:
+
+* **source**: URL des Servers, um die Datei herunterzuladen, wie kodiert`encodeURI()`.
+
+* **target**: Dateisystem-Url, das die Datei auf dem Gerät. Für rückwärts Kompatibilität, dies kann auch der vollständige Pfad der Datei auf dem Gerät sein. (Siehe [rückwärts Kompatibilität Notes] unten)
+
+* **SuccessCallback**: ein Rückruf, der übergeben wird ein `FileEntry` Objekt. *(Funktion)*
+
+* **errorCallback**: ein Rückruf, der ausgeführt wird, tritt ein Fehler beim Abrufen der `FileEntry`. Mit einem `FileTransferError`-Objekt aufgerufen. *(Funktion)*
+
+* **TrustAllHosts**: Optionaler Parameter, wird standardmäßig auf `false` . Wenn legen Sie auf `true` , es akzeptiert alle Sicherheitszertifikate. Dies ist nützlich, da Android selbstsignierte Zertifikate ablehnt. Nicht für den produktiven Einsatz empfohlen. Auf Android und iOS unterstützt. *(Boolean)*
+
+* **Options**: optionale Parameter, derzeit nur unterstützt Kopfzeilen (z. B. Autorisierung (Standardauthentifizierung), etc.).
+
+### Beispiel
+
+ // !! 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
+
+Bricht einen in-Progress-Transfer. Der Onerror-Rückruf wird ein FileTransferError-Objekt übergeben, die einen Fehlercode FileTransferError.ABORT_ERR hat.
+
+### Beispiel
+
+ // !! 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
+
+Ein `FileTransferError`-Objekt wird an eine Fehler-Callback übergeben, wenn ein Fehler auftritt.
+
+### Eigenschaften
+
+* **Code**: einer der vordefinierten Fehlercodes aufgeführt. (Anzahl)
+
+* **Quelle**: URL der Quelle. (String)
+
+* **Ziel**: URL zum Ziel. (String)
+
+* **HTTP_STATUS**: HTTP-Statuscode. Dieses Attribut ist nur verfügbar, wenn ein Response-Code aus der HTTP-Verbindung eingeht. (Anzahl)
+
+* **body** Antworttext. Dieses Attribut ist nur verfügbar, wenn eine Antwort von der HTTP-Verbindung eingeht. (String)
+
+* **exception**: entweder e.getMessage oder e.toString (String)
+
+### Konstanten
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Hinweise rückwärts Kompatibilität
+
+Frühere Versionen des Plugins würde nur Gerät-Absolute-Dateipfade als Quelle für Uploads oder als Ziel für Downloads übernehmen. Diese Pfade wäre in der Regel der form
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Für rückwärts Kompatibilität, diese Pfade noch akzeptiert werden, und wenn Ihre Anwendung Pfade wie diese im permanenten Speicher aufgezeichnet hat, dann sie können weiter verwendet werden.
+
+Diese Pfade waren zuvor in der Eigenschaft `fullPath` `FileEntry` und `DirectoryEntry`-Objekte, die durch das Plugin Datei zurückgegeben ausgesetzt. Neue Versionen der die Datei-Erweiterung, jedoch nicht länger werden diese Pfade zu JavaScript.
+
+Wenn Sie ein auf eine neue Upgrade (1.0.0 oder neuere) Version der Datei, und Sie haben zuvor mit `entry.fullPath` als Argumente `download()` oder `upload()`, dann ändern Sie den Code, um die Dateisystem-URLs verwenden müssen.
+
+`FileEntry.toURL()` und `DirectoryEntry.toURL()` zurück, eine Dateisystem-URL in der form
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+die anstelle der absoluten Dateipfad in `download()` und `upload()` Methode verwendet werden kann.
diff --git a/plugins/cordova-plugin-file-transfer/doc/es/README.md b/plugins/cordova-plugin-file-transfer/doc/es/README.md
new file mode 100644
index 0000000..1c8ee3f
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/es/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+Documentación del plugin:
+
+Este plugin te permite cargar y descargar archivos.
+
+Este plugin define global `FileTransfer` , `FileUploadOptions` constructores.
+
+Aunque en el ámbito global, no están disponibles hasta después de la `deviceready` evento.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Instalación
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Plataformas soportadas
+
+ * Amazon fire OS
+ * Android
+ * BlackBerry 10
+ * Explorador
+ * Firefox OS **
+ * iOS
+ * Windows Phone 7 y 8 *
+ * Windows 8
+ * Windows
+
+\ * *No soporta `onprogress` ni `abort()` *
+
+\ ** *No soporta `onprogress` *
+
+# FileTransfer
+
+El objeto `FileTransfer` proporciona una manera para subir archivos utilizando una varias parte solicitud HTTP POST o PUT y descargar archivos, así.
+
+## Propiedades
+
+ * **OnProgress**: llama con un `ProgressEvent` cuando se transfiere un nuevo paquete de datos. *(Función)*
+
+## Métodos
+
+ * **cargar**: envía un archivo a un servidor.
+
+ * **Descargar**: descarga un archivo del servidor.
+
+ * **abortar**: aborta una transferencia en curso.
+
+## subir
+
+**Parámetros**:
+
+ * **fileURL**: URL de Filesystem que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo)
+
+ * **servidor**: dirección URL del servidor para recibir el archivo, como codificada por`encodeURI()`.
+
+ * **successCallback**: una devolución de llamada que se pasa un `FileUploadResult` objeto. *(Función)*
+
+ * **errorCallback**: una devolución de llamada que se ejecuta si se produce un error recuperar la `FileUploadResult` . Invocado con un `FileTransferError` objeto. *(Función)*
+
+ * **Opciones**: parámetros opcionales *(objeto)*. Teclas válidas:
+
+ * **fileKey**: el nombre del elemento de formulario. Por defecto es `file` . (DOMString)
+ * **nombre de archivo**: el nombre del archivo a utilizar al guardar el archivo en el servidor. Por defecto es `image.jpg` . (DOMString)
+ * **httpMethod**: método HTTP el utilizar - o `PUT` o `POST` . Por defecto es `POST` . (DOMString)
+ * **mimeType**: el tipo mime de los datos para cargar. Por defecto es `image/jpeg` . (DOMString)
+ * **params**: un conjunto de pares clave/valor opcional para pasar en la petición HTTP. (Objeto)
+ * **chunkedMode**: Si desea cargar los datos en modo de transmisión fragmentado. Por defecto es `true` . (Boolean)
+ * **headers**: un mapa de nombre de encabezado/valores de encabezado Utilice una matriz para especificar más de un valor. En iOS FireOS y Android, si existe un encabezado llamado Content-Type, datos de un formulario multipart no se utilizará. (Object)
+ * **httpMethod**: HTTP el método a utilizar por ejemplo POST o poner. Por defecto `el POST`. (DOMString)
+
+ * **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil ya que Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)*
+
+### Ejemplo
+
+ // !! 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);
+
+
+### Ejemplo con cabeceras de subir y eventos de progreso (Android y iOS solamente)
+
+ 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` objeto se pasa a la devolución del éxito de la `FileTransfer` del objeto `upload()` método.
+
+### Propiedades
+
+ * **bytesSent**: el número de bytes enviados al servidor como parte de la carga. (largo)
+
+ * **responseCode**: código de respuesta HTTP el devuelto por el servidor. (largo)
+
+ * **respuesta**: respuesta el HTTP devuelto por el servidor. (DOMString)
+
+ * **cabeceras**: cabeceras de respuesta HTTP el por el servidor. (Objeto)
+
+ * Actualmente compatible con iOS solamente.
+
+### iOS rarezas
+
+ * No es compatible con `responseCode` o`bytesSent`.
+
+## descargar
+
+**Parámetros**:
+
+ * **fuente**: dirección URL del servidor para descargar el archivo, como codificada por`encodeURI()`.
+
+ * **objetivo**: Filesystem url que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo)
+
+ * **successCallback**: una devolución de llamada que se pasa un `FileEntry` objeto. *(Función)*
+
+ * **errorCallback**: una devolución de llamada que se ejecuta si se produce un error al recuperar los `FileEntry` . Invocado con un `FileTransferError` objeto. *(Función)*
+
+ * **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil porque Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)*
+
+ * **Opciones**: parámetros opcionales, actualmente sólo soporta cabeceras (como autorización (autenticación básica), etc.).
+
+### Ejemplo
+
+ // !! 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=="
+ }
+ }
+ );
+
+
+### Rarezas de WP8
+
+ * Descargar pide se almacena en caché por aplicación nativa. Para evitar el almacenamiento en caché, pasar `if-Modified-Since` encabezado para descargar el método.
+
+## abortar
+
+Aborta a una transferencia en curso. El callback onerror se pasa un objeto FileTransferError que tiene un código de error de FileTransferError.ABORT_ERR.
+
+### Ejemplo
+
+ // !! 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` objeto se pasa a un callback de error cuando se produce un error.
+
+### Propiedades
+
+ * **código**: uno de los códigos de error predefinido enumerados a continuación. (Número)
+
+ * **fuente**: URL a la fuente. (String)
+
+ * **objetivo**: URL a la meta. (String)
+
+ * **HTTP_STATUS**: código de estado HTTP. Este atributo sólo está disponible cuando se recibe un código de respuesta de la conexión HTTP. (Número)
+
+ * **cuerpo** Cuerpo de la respuesta. Este atributo sólo está disponible cuando se recibe una respuesta de la conexión HTTP. (String)
+
+ * **excepción**: cualquier e.getMessage o e.toString (String)
+
+### Constantes
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Al revés notas de compatibilidad
+
+Versiones anteriores de este plugin sólo aceptaría dispositivo-absoluto-archivo-rutas como la fuente de carga, o como destino para las descargas. Estos caminos normalmente sería de la forma
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Para atrás compatibilidad, estos caminos son aceptados todavía, y si su solicitud ha grabado caminos como éstos en almacenamiento persistente, entonces pueden seguir utilizarse.
+
+Estos caminos fueron expuestos anteriormente en el `fullPath` propiedad de `FileEntry` y `DirectoryEntry` objetos devueltos por el plugin de archivo. Las nuevas versiones del archivo plugin, sin embargo, ya no exponen estos caminos a JavaScript.
+
+Si va a actualizar a una nueva (1.0.0 o más reciente) versión del archivo y previamente han estado utilizando `entry.fullPath` como argumentos para `download()` o `upload()` , entonces tendrá que cambiar su código para usar URLs de sistema de archivos en su lugar.
+
+`FileEntry.toURL()`y `DirectoryEntry.toURL()` devolver un filesystem dirección URL de la forma
+
+ 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
diff --git a/plugins/cordova-plugin-file-transfer/doc/es/index.md b/plugins/cordova-plugin-file-transfer/doc/es/index.md
new file mode 100644
index 0000000..981c991
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/es/index.md
@@ -0,0 +1,262 @@
+
+
+# cordova-plugin-file-transfer
+
+Este plugin te permite cargar y descargar archivos.
+
+Este plugin define global `FileTransfer` , `FileUploadOptions` constructores.
+
+Aunque en el ámbito global, no están disponibles hasta después de la `deviceready` evento.
+
+ document.addEventListener ("deviceready", onDeviceReady, false);
+ function onDeviceReady() {console.log(FileTransfer)};
+
+
+## Instalación
+
+ Cordova plugin añade cordova-plugin-file-transferencia
+
+
+## Plataformas soportadas
+
+* Amazon fire OS
+* Android
+* BlackBerry 10
+* Explorador
+* Firefox OS **
+* iOS
+* Windows Phone 7 y 8 *
+* Windows 8
+* Windows
+
+* *No son compatibles con `onprogress` ni `abort()` *
+
+** *No son compatibles con `onprogress` *
+
+# FileTransfer
+
+El `FileTransfer` objeto proporciona una manera de subir archivos mediante una solicitud HTTP de POST varias parte y para descargar archivos.
+
+## Propiedades
+
+* **OnProgress**: llama con un `ProgressEvent` cuando se transfiere un nuevo paquete de datos. *(Función)*
+
+## Métodos
+
+* **cargar**: envía un archivo a un servidor.
+
+* **Descargar**: descarga un archivo del servidor.
+
+* **abortar**: aborta una transferencia en curso.
+
+## subir
+
+**Parámetros**:
+
+* **fileURL**: URL de Filesystem que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo)
+
+* **servidor**: dirección URL del servidor para recibir el archivo, como codificada por`encodeURI()`.
+
+* **successCallback**: una devolución de llamada que se pasa un `FileUploadResult` objeto. *(Función)*
+
+* **errorCallback**: una devolución de llamada que se ejecuta si se produce un error recuperar la `FileUploadResult` . Invocado con un `FileTransferError` objeto. *(Función)*
+
+* **Opciones**: parámetros opcionales *(objeto)*. Teclas válidas:
+
+ * **fileKey**: el nombre del elemento de formulario. Por defecto es `file` . (DOMString)
+ * **nombre de archivo**: el nombre del archivo a utilizar al guardar el archivo en el servidor. Por defecto es `image.jpg` . (DOMString)
+ * **httpMethod**: método HTTP el utilizar - o `PUT` o `POST` . Por defecto es `POST` . (DOMString)
+ * **mimeType**: el tipo mime de los datos para cargar. Por defecto es `image/jpeg` . (DOMString)
+ * **params**: un conjunto de pares clave/valor opcional para pasar en la petición HTTP. (Objeto)
+ * **chunkedMode**: Si desea cargar los datos en modo de transmisión fragmentado. Por defecto es `true` . (Boolean)
+ * **cabeceras**: un mapa de valores de encabezado nombre/cabecera. Utilice una matriz para especificar más de un valor. (Objeto)
+
+* **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil ya que Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)*
+
+### Ejemplo
+
+ // !! Asume fileURL variable contiene una dirección URL válida a un archivo de texto en el dispositivo, / / por ejemplo, ganar var cdvfile://localhost/persistent/path/to/file.txt = function (r) {console.log ("código =" + r.responseCode);
+ Console.log ("respuesta =" + r.response);
+ Console.log ("Sent =" + r.bytesSent);}
+
+ var fallar = function (error) {alert ("ha ocurrido un error: código =" + error.code);
+ Console.log ("error al cargar el origen" + error.source);
+ Console.log ("upload error objetivo" + error.target);}
+
+ var opciones = new FileUploadOptions();
+ options.fileKey = "file";
+ options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
+ options.mimeType = "text/plain";
+
+ var params = {};
+ params.value1 = "prueba";
+ params.value2 = "param";
+
+ options.params = params;
+
+ var ft = new FileTransfer();
+ Ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, opciones);
+
+
+### Ejemplo con cabeceras de subir y eventos de progreso (Android y iOS solamente)
+
+ function win(r) {console.log ("código =" + r.responseCode);
+ Console.log ("respuesta =" + r.response);
+ Console.log ("Sent =" + r.bytesSent);}
+
+ function fail(error) {alert ("ha ocurrido un error: código =" + error.code);
+ Console.log ("error al cargar el origen" + error.source);
+ Console.log ("upload error objetivo" + error.target);}
+
+ var uri = encodeURI ("http://some.server.com/upload.php");
+
+ var opciones = new FileUploadOptions();
+ options.fileKey="file";
+ options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
+ options.mimeType="text/plain";
+
+ cabeceras de var ={'headerParam':'headerValue'};
+
+ options.headers = encabezados;
+
+ var ft = new FileTransfer();
+ Ft.OnProgress = function(progressEvent) {si (progressEvent.lengthComputable) {loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
+ } {loadingStatus.increment() más;
+ }
+ };
+ Ft.upload (fileURL, uri, win, fail, opciones);
+
+
+## FileUploadResult
+
+A `FileUploadResult` objeto se pasa a la devolución del éxito de la `FileTransfer` del objeto `upload()` método.
+
+### Propiedades
+
+* **bytesSent**: el número de bytes enviados al servidor como parte de la carga. (largo)
+
+* **responseCode**: código de respuesta HTTP el devuelto por el servidor. (largo)
+
+* **respuesta**: respuesta el HTTP devuelto por el servidor. (DOMString)
+
+* **cabeceras**: cabeceras de respuesta HTTP el por el servidor. (Objeto)
+
+ * Actualmente compatible con iOS solamente.
+
+### iOS rarezas
+
+* No es compatible con `responseCode` o`bytesSent`.
+
+## descargar
+
+**Parámetros**:
+
+* **fuente**: dirección URL del servidor para descargar el archivo, como codificada por`encodeURI()`.
+
+* **objetivo**: Filesystem url que representa el archivo en el dispositivo. Para atrás compatibilidad, esto también puede ser la ruta de acceso completa del archivo en el dispositivo. (Ver [hacia atrás compatibilidad notas] debajo)
+
+* **successCallback**: una devolución de llamada que se pasa un `FileEntry` objeto. *(Función)*
+
+* **errorCallback**: una devolución de llamada que se ejecuta si se produce un error al recuperar los `FileEntry` . Invocado con un `FileTransferError` objeto. *(Función)*
+
+* **trustAllHosts**: parámetro opcional, por defecto es `false` . Si establece en `true` , acepta todos los certificados de seguridad. Esto es útil porque Android rechaza certificados autofirmados seguridad. No se recomienda para uso productivo. Compatible con iOS y Android. *(boolean)*
+
+* **Opciones**: parámetros opcionales, actualmente sólo soporta cabeceras (como autorización (autenticación básica), etc.).
+
+### Ejemplo
+
+ // !! Asume fileURL variable contiene una dirección URL válida a un camino en el dispositivo, / / por ejemplo, File Transfer var cdvfile://localhost/persistent/path/to/downloads/ = new FileTransfer();
+ var uri = encodeURI ("http://some.server.com/download.php");
+
+ fileTransfer.download (uri, fileURL, function(entry) {console.log ("descarga completa:" + entry.toURL());
+ }, function(error) {console.log ("error al descargar el origen" + error.source);
+ Console.log ("descargar error objetivo" + error.target);
+ Console.log ("código de error de carga" + error.code);
+ }, falso, {encabezados: {"Autorización": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA =="}});
+
+
+## abortar
+
+Aborta a una transferencia en curso. El callback onerror se pasa un objeto FileTransferError que tiene un código de error de FileTransferError.ABORT_ERR.
+
+### Ejemplo
+
+ // !! Asume fileURL variable contiene una dirección URL válida a un archivo de texto en el dispositivo, / / por ejemplo, ganar cdvfile://localhost/persistent/path/to/file.txt var function(r) = {console.log ("no se debe llamar.");}
+
+ var fallar = function(error) {/ / error.code == FileTransferError.ABORT_ERR alert ("ha ocurrido un error: código =" + error.code);
+ Console.log ("error al cargar el origen" + error.source);
+ Console.log ("upload error objetivo" + error.target);}
+
+ var opciones = 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, opciones);
+ Ft.Abort();
+
+
+## FileTransferError
+
+A `FileTransferError` objeto se pasa a un callback de error cuando se produce un error.
+
+### Propiedades
+
+* **código**: uno de los códigos de error predefinido enumerados a continuación. (Número)
+
+* **fuente**: URL a la fuente. (String)
+
+* **objetivo**: URL a la meta. (String)
+
+* **HTTP_STATUS**: código de estado HTTP. Este atributo sólo está disponible cuando se recibe un código de respuesta de la conexión HTTP. (Número)
+
+* **cuerpo** Cuerpo de la respuesta. Este atributo sólo está disponible cuando se recibe una respuesta de la conexión HTTP. (String)
+
+* **excepción**: cualquier e.getMessage o e.toString (String)
+
+### Constantes
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Al revés notas de compatibilidad
+
+Versiones anteriores de este plugin sólo aceptaría dispositivo-absoluto-archivo-rutas como la fuente de carga, o como destino para las descargas. Estos caminos normalmente sería de la forma
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Para atrás compatibilidad, estos caminos son aceptados todavía, y si su solicitud ha grabado caminos como éstos en almacenamiento persistente, entonces pueden seguir utilizarse.
+
+Estos caminos fueron expuestos anteriormente en el `fullPath` propiedad de `FileEntry` y `DirectoryEntry` objetos devueltos por el plugin de archivo. Las nuevas versiones del archivo plugin, sin embargo, ya no exponen estos caminos a JavaScript.
+
+Si va a actualizar a una nueva (1.0.0 o más reciente) versión del archivo y previamente han estado utilizando `entry.fullPath` como argumentos para `download()` o `upload()` , entonces tendrá que cambiar su código para usar URLs de sistema de archivos en su lugar.
+
+`FileEntry.toURL()`y `DirectoryEntry.toURL()` devolver un filesystem dirección URL de la forma
+
+ 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.
diff --git a/plugins/cordova-plugin-file-transfer/doc/fr/README.md b/plugins/cordova-plugin-file-transfer/doc/fr/README.md
new file mode 100644
index 0000000..ca3e18a
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/fr/README.md
@@ -0,0 +1,270 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+Documentation du plugin :
+
+Ce plugin vous permet de télécharger des fichiers.
+
+Ce plugin définit global `FileTransfer` , `FileUploadOptions` constructeurs.
+
+Bien que dans la portée globale, ils ne sont pas disponibles jusqu'après la `deviceready` événement.
+
+ document.addEventListener (« deviceready », onDeviceReady, false) ;
+ function onDeviceReady() {console.log(FileTransfer);}
+
+
+## Installation
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Plates-formes supportées
+
+ * Amazon Fire OS
+ * Android
+ * BlackBerry 10
+ * Navigateur
+ * Firefox OS **
+ * iOS
+ * Windows Phone 7 et 8 *
+ * Windows 8
+ * Windows
+
+\ * *Ne supportent pas `onprogress` ni `abort()` *
+
+\ ** *Ne prennent pas en charge les `onprogress` *
+
+# Transfert de fichiers
+
+L'objet de `FileTransfer` fournit un moyen de télécharger des fichiers à l'aide d'une requête HTTP multi-part POST ou PUT et pour télécharger des fichiers.
+
+## Propriétés
+
+ * **onprogress** : fonction appelée avec un `ProgressEvent` à chaque fois qu'un nouveau segment de données est transféré. *(Function)*
+
+## Méthodes
+
+ * **upload** : envoie un fichier à un serveur.
+
+ * **download** : télécharge un fichier depuis un serveur.
+
+ * **abort** : annule le transfert en cours.
+
+## upload
+
+**Paramètres**:
+
+ * **fileURL** : système de fichiers URL représentant le fichier sur le périphérique. Pour la compatibilité ascendante, cela peut aussi être le chemin complet du fichier sur le périphérique. (Voir [Backwards Compatibility Notes] ci-dessous)
+
+ * **server** : l'URL du serveur destiné à recevoir le fichier, encodée via `encodeURI()`.
+
+ * **successCallback**: un rappel passé un `FileUploadResult` objet. *(Fonction)*
+
+ * **errorCallback**: un rappel qui s'exécute si une erreur survient récupérer la `FileUploadResult` . Appelée avec un `FileTransferError` objet. *(Fonction)*
+
+ * **options**: paramètres facultatifs *(objet)*. Clés valides :
+
+ * **fileKey**: le nom de l'élément form. Valeur par défaut est `file` . (DOMString)
+ * **fileName**: le nom de fichier à utiliser lorsque vous enregistrez le fichier sur le serveur. Valeur par défaut est `image.jpg` . (DOMString)
+ * **httpMethod**: méthode de The HTTP à utiliser - soit `PUT` ou `POST` . Valeur par défaut est `POST` . (DOMString)
+ * **type MIME**: le type mime des données à télécharger. Valeur par défaut est `image/jpeg` . (DOMString)
+ * **params**: un ensemble de paires clé/valeur facultative pour passer dans la requête HTTP. (Objet)
+ * **chunkedMode**: s'il faut télécharger les données en mode streaming mémorisé en bloc. Valeur par défaut est `true` . (Boolean)
+ * **headers**: une carte des valeurs d'en-tête en-tête/nom. Un tableau permet de spécifier plusieurs valeurs. Sur iOS, FireOS et Android, si un en-tête nommé Content-Type n'est présent, les données de formulaire multipart servira pas. (Object)
+ * **httpMethod**: The HTTP méthode à utiliser par exemple poster ou mis. Par défaut, `message`. (DOMString)
+
+ * **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur est `true` , il accepte tous les certificats de sécurité. Ceci est utile car Android rejette des certificats auto-signés. N'est pas recommandé pour une utilisation en production. Supporté sur Android et iOS. *(booléen)*
+
+### Exemple
+
+ // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function (r) {console.log ("Code =" + r.responseCode) ;
+ Console.log ("réponse =" + r.response) ;
+ Console.log ("envoyés =" + r.bytesSent);}
+
+ échouer var = function (erreur) {alert ("une erreur est survenue : Code =" + error.code) ;
+ Console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log ("erreur de téléchargement cible" + error.target);}
+
+ options de var = new FileUploadOptions() ;
+ options.fileKey = « fichier » ;
+ options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1) ;
+ options.mimeType = « text/plain » ;
+
+ var params = {} ;
+ params.value1 = « test » ;
+ params.Value2 = « param » ;
+
+ options.params = params ;
+
+ ft var = new FileTransfer() ;
+ ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ;
+
+
+### Exemple avec téléchargement du Header et des Progress Events (Android et iOS uniquement)
+
+ function win(r) {console.log ("Code =" + r.responseCode) ;
+ Console.log ("réponse =" + r.response) ;
+ Console.log ("envoyés =" + r.bytesSent);}
+
+ function fail(error) {alert ("une erreur est survenue : Code =" + error.code) ;
+ Console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log ("erreur de téléchargement cible" + error.target);}
+
+ var uri = encodeURI ("http://some.server.com/upload.php") ;
+
+ options de var = new FileUploadOptions() ;
+ options.fileKey="file" ;
+ options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1) ;
+ options.mimeType="text/plain" ;
+
+ en-têtes var ={'headerParam':'headerValue'} ;
+
+ options.Headers = en-têtes ;
+
+ ft var = new FileTransfer() ;
+ ft.OnProgress = function(progressEvent) {si (progressEvent.lengthComputable) {loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total) ;
+ } else {loadingStatus.increment() ;
+ }
+ };
+ ft.upload (fileURL, uri, win, fail, options) ;
+
+
+## FileUploadResult
+
+A `FileUploadResult` objet est passé au rappel de succès la `FileTransfer` de l'objet `upload()` méthode.
+
+### Propriétés
+
+ * **bytesSent** : le nombre d'octets envoyés au serveur dans le cadre du téléchargement. (long)
+
+ * **responseCode** : le code de réponse HTTP retourné par le serveur. (long)
+
+ * **response** : la réponse HTTP renvoyée par le serveur. (DOMString)
+
+ * **en-têtes** : en-têtes de réponse HTTP par le serveur. (Objet)
+
+ * Actuellement pris en charge sur iOS seulement.
+
+### Notes au sujet d'iOS
+
+ * Ne prend pas en charge les propriétés `responseCode` et `bytesSent`.
+
+## download
+
+**Paramètres**:
+
+ * **source** : l'URL du serveur depuis lequel télécharger le fichier, encodée via `encodeURI()`.
+
+ * **target** : système de fichiers url représentant le fichier sur le périphérique. Pour la compatibilité ascendante, cela peut aussi être le chemin complet du fichier sur le périphérique. (Voir [Backwards Compatibility Notes] ci-dessous)
+
+ * **successCallback** : une callback de succès à laquelle est passée un objet `FileEntry`. *(Function)*
+
+ * **errorCallback**: un rappel qui s'exécute si une erreur se produit lors de la récupération du `FileEntry` . Appelée avec un `FileTransferError` objet. *(Fonction)*
+
+ * **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur est `true` , il accepte tous les certificats de sécurité. Ceci peut être utile car Android rejette les certificats auto-signés. N'est pas recommandé pour une utilisation en production. Supporté sur Android et iOS. *(booléen)*
+
+ * **options** : paramètres facultatifs, seules les en-têtes sont actuellement supportées (par exemple l'autorisation (authentification basique), etc.).
+
+### Exemple
+
+ // !! Suppose fileURL variable contient une URL valide vers un chemin d'accès sur le périphérique, / / par exemple, transfert de fichiers var cdvfile://localhost/persistent/path/to/downloads/ = new FileTransfer() ;
+ var uri = encodeURI ("http://some.server.com/download.php") ;
+
+ fileTransfer.download (uri, fileURL, function(entry) {console.log ("téléchargement complet:" + entry.toURL()) ;
+ }, function(error) {console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log (« erreur de téléchargement cible » + error.target) ;
+ Console.log (« code d'erreur de téléchargement » + error.code) ;
+ }, faux, {en-têtes: {« Autorisation »: « dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA base == "}}) ;
+
+
+### Quirks wp8
+
+ * Télécharger demande est mis en cache par l'implémentation native. Pour éviter la mise en cache, pass `if-Modified-Since` en-tête Télécharger méthode.
+
+## abort
+
+Abandonne un transfert en cours. Le rappel onerror est passé à un objet FileTransferError qui a un code d'erreur de FileTransferError.ABORT_ERR.
+
+### Exemple
+
+ // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function(r) {console.log ("ne devrait pas être appelée.");}
+
+ var fail = function(error) {/ / error.code == FileTransferError.ABORT_ERR alert ("une erreur est survenue : Code =" + error.code) ;
+ Console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log ("erreur de téléchargement cible" + error.target);}
+
+ options de var = new FileUploadOptions() ;
+ options.fileKey="file" ;
+ options.fileName="myphoto.jpg" ;
+ options.mimeType="image/jpeg" ;
+
+ ft var = new FileTransfer() ;
+ ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ;
+ ft.Abort() ;
+
+
+## FileTransferError
+
+A `FileTransferError` objet est passé à un rappel d'erreur lorsqu'une erreur survient.
+
+### Propriétés
+
+ * **code** : l'un des codes d'erreur prédéfinis énumérés ci-dessous. (Number)
+
+ * **source** : l'URI de la source. (String)
+
+ * **target**: l'URI de la destination. (String)
+
+ * **http_status** : code d'état HTTP. Cet attribut n'est disponible que lorsqu'un code de réponse est fourni via la connexion HTTP. (Number)
+
+ * **corps** Corps de réponse. Cet attribut n'est disponible que lorsqu'une réponse est reçue de la connexion HTTP. (String)
+
+ * **exception**: soit e.getMessage ou e.toString (String)
+
+### Constantes
+
+ * 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
+
+Les versions précédentes de ce plugin n'accepterait périphérique--fichier-chemins d'accès absolus comme source pour les téléchargements, ou comme cible pour les téléchargements. Ces chemins seraient généralement de la forme
+
+ / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android)
+
+
+Pour vers l'arrière la compatibilité, ces chemins sont toujours acceptés, et si votre application a enregistré des chemins comme celles-ci dans un stockage persistant, alors ils peuvent continuer à être utilisé.
+
+Ces chemins ont été précédemment exposés dans le `fullPath` propriété de `FileEntry` et `DirectoryEntry` les objets retournés par le fichier plugin. Nouvelles versions du fichier plugin, cependant, ne plus exposent ces chemins à JavaScript.
+
+Si vous migrez vers une nouvelle (1.0.0 ou plus récent) version de fichier et vous avez précédemment utilisé `entry.fullPath` comme arguments à `download()` ou `upload()` , alors vous aurez besoin de modifier votre code pour utiliser le système de fichiers URL au lieu de cela.
+
+`FileEntry.toURL()`et `DirectoryEntry.toURL()` retournent une URL de système de fichiers du formulaire
+
+ 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
diff --git a/plugins/cordova-plugin-file-transfer/doc/fr/index.md b/plugins/cordova-plugin-file-transfer/doc/fr/index.md
new file mode 100644
index 0000000..6b2bce0
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/fr/index.md
@@ -0,0 +1,261 @@
+
+
+# cordova-plugin-file-transfer
+
+Ce plugin vous permet de télécharger des fichiers.
+
+Ce plugin définit global `FileTransfer` , `FileUploadOptions` constructeurs.
+
+Bien que dans la portée globale, ils ne sont pas disponibles jusqu'après la `deviceready` événement.
+
+ document.addEventListener (« deviceready », onDeviceReady, false) ;
+ function onDeviceReady() {console.log(FileTransfer);}
+
+
+## Installation
+
+ Cordova plugin ajouter cordova-plugin-file-transfert
+
+
+## Plates-formes prises en charge
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Navigateur
+* Firefox OS **
+* iOS
+* Windows Phone 7 et 8 *
+* Windows 8
+* Windows
+
+* *Ne supportent pas `onprogress` ni `abort()` *
+
+** *Ne prennent pas en charge `onprogress` *
+
+# Transfert de fichiers
+
+Le `FileTransfer` objet fournit un moyen de télécharger des fichiers à l'aide d'une requête HTTP de la poste plusieurs partie et pour télécharger des fichiers aussi bien.
+
+## Propriétés
+
+* **onprogress** : fonction appelée avec un `ProgressEvent` à chaque fois qu'un nouveau segment de données est transféré. *(Function)*
+
+## Méthodes
+
+* **upload** : envoie un fichier à un serveur.
+
+* **download** : télécharge un fichier depuis un serveur.
+
+* **abort** : annule le transfert en cours.
+
+## upload
+
+**Paramètres**:
+
+* **fileURL** : système de fichiers URL représentant le fichier sur le périphérique. Pour la compatibilité ascendante, cela peut aussi être le chemin complet du fichier sur le périphérique. (Voir [Backwards Compatibility Notes] ci-dessous)
+
+* **server** : l'URL du serveur destiné à recevoir le fichier, encodée via `encodeURI()`.
+
+* **successCallback**: un rappel passé un `FileUploadResult` objet. *(Fonction)*
+
+* **errorCallback**: un rappel qui s'exécute si une erreur survient récupérer la `FileUploadResult` . Appelée avec un `FileTransferError` objet. *(Fonction)*
+
+* **options**: paramètres facultatifs *(objet)*. Clés valides :
+
+ * **fileKey**: le nom de l'élément form. Valeur par défaut est `file` . (DOMString)
+ * **fileName**: le nom de fichier à utiliser lorsque vous enregistrez le fichier sur le serveur. Valeur par défaut est `image.jpg` . (DOMString)
+ * **httpMethod**: méthode de The HTTP à utiliser - soit `PUT` ou `POST` . Valeur par défaut est `POST` . (DOMString)
+ * **type MIME**: le type mime des données à télécharger. Valeur par défaut est `image/jpeg` . (DOMString)
+ * **params**: un ensemble de paires clé/valeur facultative pour passer dans la requête HTTP. (Objet)
+ * **chunkedMode**: s'il faut télécharger les données en mode streaming mémorisé en bloc. Valeur par défaut est `true` . (Boolean)
+ * **en-têtes**: une carte des valeurs d'en-tête en-tête/nom. Un tableau permet de spécifier plusieurs valeurs. (Objet)
+
+* **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur `true` , il accepte tous les certificats de sécurité. Ceci est utile car Android rejette des certificats auto-signés. Non recommandé pour une utilisation de production. Supporté sur Android et iOS. *(boolean)*
+
+### Exemple
+
+ // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function (r) {console.log ("Code =" + r.responseCode) ;
+ Console.log ("réponse =" + r.response) ;
+ Console.log ("envoyés =" + r.bytesSent);}
+
+ échouer var = function (erreur) {alert ("une erreur est survenue : Code =" + error.code) ;
+ Console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log ("erreur de téléchargement cible" + error.target);}
+
+ options de var = new FileUploadOptions() ;
+ options.fileKey = « fichier » ;
+ options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1) ;
+ options.mimeType = « text/plain » ;
+
+ var params = {} ;
+ params.value1 = « test » ;
+ params.Value2 = « param » ;
+
+ options.params = params ;
+
+ ft var = new FileTransfer() ;
+ ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ;
+
+
+### Exemple avec téléchargement du Header et des Progress Events (Android et iOS uniquement)
+
+ function win(r) {console.log ("Code =" + r.responseCode) ;
+ Console.log ("réponse =" + r.response) ;
+ Console.log ("envoyés =" + r.bytesSent);}
+
+ function fail(error) {alert ("une erreur est survenue : Code =" + error.code) ;
+ Console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log ("erreur de téléchargement cible" + error.target);}
+
+ var uri = encodeURI ("http://some.server.com/upload.php") ;
+
+ options de var = new FileUploadOptions() ;
+ options.fileKey="file" ;
+ options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1) ;
+ options.mimeType="text/plain" ;
+
+ en-têtes var ={'headerParam':'headerValue'} ;
+
+ options.Headers = en-têtes ;
+
+ ft var = new FileTransfer() ;
+ ft.OnProgress = function(progressEvent) {si (progressEvent.lengthComputable) {loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total) ;
+ } else {loadingStatus.increment() ;
+ }
+ };
+ ft.upload (fileURL, uri, win, fail, options) ;
+
+
+## FileUploadResult
+
+A `FileUploadResult` objet est passé au rappel de succès la `FileTransfer` de l'objet `upload()` méthode.
+
+### Propriétés
+
+* **bytesSent** : le nombre d'octets envoyés au serveur dans le cadre du téléchargement. (long)
+
+* **responseCode** : le code de réponse HTTP retourné par le serveur. (long)
+
+* **response** : la réponse HTTP renvoyée par le serveur. (DOMString)
+
+* **en-têtes** : en-têtes de réponse HTTP par le serveur. (Objet)
+
+ * Actuellement pris en charge sur iOS seulement.
+
+### iOS Remarques
+
+* Ne prend pas en charge les propriétés `responseCode` et `bytesSent`.
+
+## download
+
+**Paramètres**:
+
+* **source** : l'URL du serveur depuis lequel télécharger le fichier, encodée via `encodeURI()`.
+
+* **target** : système de fichiers url représentant le fichier sur le périphérique. Pour vers l'arrière la compatibilité, cela peut aussi être le chemin d'accès complet du fichier sur le périphérique. (Voir [vers l'arrière compatibilité note] ci-dessous)
+
+* **successCallback** : une callback de succès à laquelle est passée un objet `FileEntry`. *(Function)*
+
+* **errorCallback**: un rappel qui s'exécute si une erreur se produit lors de la récupération du `FileEntry` . Appelée avec un `FileTransferError` objet. *(Fonction)*
+
+* **trustAllHosts**: paramètre facultatif, valeur par défaut est `false` . Si la valeur est `true` , il accepte tous les certificats de sécurité. Ceci peut être utile car Android rejette les certificats auto-signés. N'est pas recommandé pour une utilisation en production. Supporté sur Android et iOS. *(booléen)*
+
+* **options** : paramètres facultatifs, seules les en-têtes sont actuellement supportées (par exemple l'autorisation (authentification basique), etc.).
+
+### Exemple
+
+ // !! Suppose fileURL variable contient une URL valide vers un chemin d'accès sur le périphérique, / / par exemple, transfert de fichiers var cdvfile://localhost/persistent/path/to/downloads/ = new FileTransfer() ;
+ var uri = encodeURI ("http://some.server.com/download.php") ;
+
+ fileTransfer.download (uri, fileURL, function(entry) {console.log ("téléchargement complet:" + entry.toURL()) ;
+ }, function(error) {console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log (« erreur de téléchargement cible » + error.target) ;
+ Console.log (« code d'erreur de téléchargement » + error.code) ;
+ }, faux, {en-têtes: {« Autorisation »: « dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA base == "}}) ;
+
+
+## abort
+
+Abandonne un transfert en cours. Le rappel onerror est passé à un objet FileTransferError qui a un code d'erreur de FileTransferError.ABORT_ERR.
+
+### Exemple
+
+ // !! Suppose fileURL variable contient une URL valide dans un fichier texte sur le périphérique, / / par exemple, cdvfile://localhost/persistent/path/to/file.txt var win = function(r) {console.log ("ne devrait pas être appelée.");}
+
+ var fail = function(error) {/ / error.code == FileTransferError.ABORT_ERR alert ("une erreur est survenue : Code =" + error.code) ;
+ Console.log (« source de l'erreur de téléchargement » + error.source) ;
+ Console.log ("erreur de téléchargement cible" + error.target);}
+
+ options de var = new FileUploadOptions() ;
+ options.fileKey="file" ;
+ options.fileName="myphoto.jpg" ;
+ options.mimeType="image/jpeg" ;
+
+ ft var = new FileTransfer() ;
+ ft.upload (fileURL, encodeURI ("http://some.server.com/upload.php"), win, fail, options) ;
+ ft.Abort() ;
+
+
+## FileTransferError
+
+A `FileTransferError` objet est passé à un rappel d'erreur lorsqu'une erreur survient.
+
+### Propriétés
+
+* **code** : l'un des codes d'erreur prédéfinis énumérés ci-dessous. (Number)
+
+* **source** : l'URI de la source. (String)
+
+* **target**: l'URI de la destination. (String)
+
+* **http_status** : code d'état HTTP. Cet attribut n'est disponible que lorsqu'un code de réponse est fourni via la connexion HTTP. (Number)
+
+* **corps** Corps de réponse. Cet attribut n'est disponible que lorsqu'une réponse est reçue de la connexion HTTP. (String)
+
+* **exception**: soit e.getMessage ou e.toString (String)
+
+### Constantes
+
+* 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
+
+Les versions précédentes de ce plugin n'accepterait périphérique--fichier-chemins d'accès absolus comme source pour les téléchargements, ou comme cible pour les téléchargements. Ces chemins seraient généralement de la forme
+
+ / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android)
+
+
+Pour vers l'arrière la compatibilité, ces chemins sont toujours acceptés, et si votre application a enregistré des chemins comme celles-ci dans un stockage persistant, alors ils peuvent continuer à être utilisé.
+
+Ces chemins ont été précédemment exposés dans le `fullPath` propriété de `FileEntry` et `DirectoryEntry` les objets retournés par le fichier plugin. Nouvelles versions du fichier plugin, cependant, ne plus exposent ces chemins à JavaScript.
+
+Si vous migrez vers une nouvelle (1.0.0 ou plus récent) version de fichier et vous avez précédemment utilisé `entry.fullPath` comme arguments à `download()` ou `upload()` , alors vous aurez besoin de modifier votre code pour utiliser le système de fichiers URL au lieu de cela.
+
+`FileEntry.toURL()`et `DirectoryEntry.toURL()` retournent une URL de système de fichiers du formulaire
+
+ 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.
diff --git a/plugins/cordova-plugin-file-transfer/doc/it/README.md b/plugins/cordova-plugin-file-transfer/doc/it/README.md
new file mode 100644
index 0000000..74d4ef5
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/it/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+Documentazione plugin:
+
+Questo plugin permette di caricare e scaricare file.
+
+Questo plugin definisce globale `FileTransfer`, costruttori di `FileUploadOptions`.
+
+Anche se in ambito globale, non sono disponibili fino a dopo l'evento `deviceready`.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Installazione
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Piattaforme supportate
+
+ * Amazon fuoco OS
+ * Android
+ * BlackBerry 10
+ * Browser
+ * Firefox OS**
+ * iOS
+ * Windows Phone 7 e 8 *
+ * Windows 8
+ * Windows
+
+\ * *Non supportano `onprogress` né `abort()` *
+
+\ * * *Non supportano `onprogress` *
+
+# FileTransfer
+
+L'oggetto `FileTransfer` fornisce un modo per caricare i file utilizzando una richiesta HTTP multiparte POST o PUT e scaricare file pure.
+
+## Proprietà
+
+ * **OnProgress**: chiamata con un `ProgressEvent` ogni volta che un nuovo blocco di dati viene trasferito. *(Funzione)*
+
+## Metodi
+
+ * **caricare**: invia un file a un server.
+
+ * **Scarica**: Scarica un file dal server.
+
+ * **Abort**: interrompe un trasferimento in corso.
+
+## upload
+
+**Parametri**:
+
+ * **fileURL**: Filesystem URL che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto)
+
+ * **server**: URL del server per ricevere il file, come codificato dal`encodeURI()`.
+
+ * **successCallback**: un callback che viene passato un oggetto `FileUploadResult`. *(Funzione)*
+
+ * **errorCallback**: un callback che viene eseguito se si verifica un errore di recupero `FileUploadResult`. Richiamato con un oggetto `FileTransferError`. *(Funzione)*
+
+ * **opzioni**: parametri facoltativi *(oggetto)*. Chiavi valide:
+
+ * **fileKey**: il nome dell'elemento form. Valore predefinito è `file` . (DOMString)
+ * **nome file**: il nome del file da utilizzare quando si salva il file sul server. Valore predefinito è `image.jpg` . (DOMString)
+ * **httpMethod**: metodo HTTP da utilizzare - `PUT` o `POST`. Impostazioni predefinite per `POST`. (DOMString)
+ * **mimeType**: il tipo mime dei dati da caricare. Impostazioni predefinite su `image/jpeg`. (DOMString)
+ * **params**: un insieme di coppie chiave/valore opzionale per passare nella richiesta HTTP. (Object)
+ * **chunkedMode**: se a caricare i dati in modalità streaming chunked. Impostazione predefinita è `true`. (Boolean)
+ * **headers**: una mappa di valori di intestazione e nome dell'intestazione. Utilizzare una matrice per specificare più di un valore. Su iOS, FireOS e Android, se è presente, un'intestazione Content-Type il nome dati form multipart non verranno utilizzati. (Object)
+ * **httpMethod**: metodo HTTP da utilizzare per esempio POST o PUT. Il valore predefinito è `POST`. (DOMString)
+
+ * **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile poiché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)*
+
+### Esempio
+
+ // !! 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);
+
+
+### Esempio con intestazioni di caricare ed eventi Progress (Android e iOS solo)
+
+ 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
+
+Un oggetto `FileUploadResult` viene passato al metodo di callback del metodo `upload()` dell'oggetto `FileTransfer` successo.
+
+### Proprietà
+
+ * **bytesSent**: il numero di byte inviati al server come parte dell'upload. (lungo)
+
+ * **responseCode**: codice di risposta HTTP restituito dal server. (lungo)
+
+ * **risposta**: risposta HTTP restituito dal server. (DOMString)
+
+ * **intestazioni**: intestazioni di risposta HTTP dal server. (Oggetto)
+
+ * Attualmente supportato solo iOS.
+
+### iOS stranezze
+
+ * Non supporta `responseCode` o`bytesSent`.
+
+## Scarica
+
+**Parametri**:
+
+ * **fonte**: URL del server per scaricare il file, come codificato dal`encodeURI()`.
+
+ * **destinazione**: Filesystem url che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto)
+
+ * **successCallback**: un callback passato un `FileEntry` oggetto. *(Funzione)*
+
+ * **errorCallback**: un callback che viene eseguito se si verifica un errore durante il recupero `FileEntry`. Richiamato con un oggetto `FileTransferError`. *(Function)*
+
+ * **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile perché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)*
+
+ * **opzioni**: parametri facoltativi, attualmente solo supporti intestazioni (ad esempio autorizzazione (autenticazione di base), ecc.).
+
+### Esempio
+
+ // !! 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 stranezze
+
+ * Il download richiede è nella cache di implementazione nativa. Per evitare la memorizzazione nella cache, passare `if-Modified-Since` intestazione per metodo di download.
+
+## Abort
+
+Interrompe un trasferimento in corso. Il callback onerror viene passato un oggetto FileTransferError che presenta un codice di errore di FileTransferError.ABORT_ERR.
+
+### Esempio
+
+ // !! 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
+
+Un oggetto `FileTransferError` viene passato a un callback di errore quando si verifica un errore.
+
+### Proprietà
+
+ * **codice**: uno dei codici di errore predefiniti elencati di seguito. (Numero)
+
+ * **fonte**: URL all'origine. (String)
+
+ * **destinazione**: URL di destinazione. (String)
+
+ * **http_status**: codice di stato HTTP. Questo attributo è disponibile solo quando viene ricevuto un codice di risposta della connessione HTTP. (Numero)
+
+ * **body** Corpo della risposta. Questo attributo è disponibile solo quando viene ricevuta una risposta dalla connessione HTTP. (String)
+
+ * **exception**: O e.getMessage o e.toString (String)
+
+### Costanti
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Note di compatibilità all'indietro
+
+Versioni precedenti di questo plugin accetterebbe solo dispositivo-assoluto-percorsi di file come origine per upload, o come destinazione per il download. Questi percorsi si sarebbero generalmente di forma
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Per indietro compatibilità, questi percorsi sono ancora accettati, e se l'applicazione ha registrato percorsi come questi in un archivio permanente, quindi possono continuare a essere utilizzato.
+
+Questi percorsi sono stati precedentemente esposti nella proprietà `fullPath` di `FileEntry` e oggetti `DirectoryEntry` restituiti dal File plugin. Nuove versioni del File plugin, tuttavia, non è più espongono questi percorsi a JavaScript.
+
+Se si esegue l'aggiornamento a una nuova (1.0.0 o più recente) versione del File e si hanno precedentemente utilizzato `entry.fullPath` come argomenti per `download()` o `upload()`, quindi sarà necessario cambiare il codice per utilizzare gli URL filesystem invece.
+
+`FileEntry.toURL()` e `DirectoryEntry.toURL()` restituiscono un filesystem URL del modulo
+
+ 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
diff --git a/plugins/cordova-plugin-file-transfer/doc/it/index.md b/plugins/cordova-plugin-file-transfer/doc/it/index.md
new file mode 100644
index 0000000..e1b74e3
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/it/index.md
@@ -0,0 +1,302 @@
+
+
+# cordova-plugin-file-transfer
+
+Questo plugin permette di caricare e scaricare file.
+
+Questo plugin definisce globale `FileTransfer`, costruttori di `FileUploadOptions`.
+
+Anche se in ambito globale, non sono disponibili fino a dopo l'evento `deviceready`.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Installazione
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Piattaforme supportate
+
+* Amazon fuoco OS
+* Android
+* BlackBerry 10
+* Browser
+* Firefox OS**
+* iOS
+* Windows Phone 7 e 8 *
+* Windows 8
+* Windows
+
+* *Supporto `onprogress` né `abort()`*
+
+** *Non supportano `onprogress`*
+
+# FileTransfer
+
+L'oggetto `FileTransfer` fornisce un modo per caricare i file utilizzando una richiesta HTTP di POST più parte e scaricare file pure.
+
+## Proprietà
+
+* **OnProgress**: chiamata con un `ProgressEvent` ogni volta che un nuovo blocco di dati viene trasferito. *(Funzione)*
+
+## Metodi
+
+* **caricare**: invia un file a un server.
+
+* **Scarica**: Scarica un file dal server.
+
+* **Abort**: interrompe un trasferimento in corso.
+
+## caricare
+
+**Parametri**:
+
+* **fileURL**: Filesystem URL che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto)
+
+* **server**: URL del server per ricevere il file, come codificato dal`encodeURI()`.
+
+* **successCallback**: un callback che viene passato un oggetto `FileUploadResult`. *(Funzione)*
+
+* **errorCallback**: un callback che viene eseguito se si verifica un errore di recupero `FileUploadResult`. Richiamato con un oggetto `FileTransferError`. *(Funzione)*
+
+* **opzioni**: parametri facoltativi *(oggetto)*. Chiavi valide:
+
+ * **fileKey**: il nome dell'elemento form. Valore predefinito è `file` . (DOMString)
+ * **nome file**: il nome del file da utilizzare quando si salva il file sul server. Valore predefinito è `image.jpg` . (DOMString)
+ * **httpMethod**: metodo HTTP da utilizzare - `PUT` o `POST`. Impostazioni predefinite per `POST`. (DOMString)
+ * **mimeType**: il tipo mime dei dati da caricare. Impostazioni predefinite su `image/jpeg`. (DOMString)
+ * **params**: un insieme di coppie chiave/valore opzionale per passare nella richiesta HTTP. (Object)
+ * **chunkedMode**: se a caricare i dati in modalità streaming chunked. Impostazione predefinita è `true`. (Boolean)
+ * **headers**: mappa di valori nome/intestazione intestazione. Utilizzare una matrice per specificare più valori. (Object)
+
+* **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile poiché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)*
+
+### Esempio
+
+ // !! 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);
+
+
+### Esempio con intestazioni di caricare ed eventi Progress (Android e iOS solo)
+
+ 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
+
+Un oggetto `FileUploadResult` viene passato al metodo di callback del metodo `upload()` dell'oggetto `FileTransfer` successo.
+
+### Proprietà
+
+* **bytesSent**: il numero di byte inviati al server come parte dell'upload. (lungo)
+
+* **responseCode**: codice di risposta HTTP restituito dal server. (lungo)
+
+* **risposta**: risposta HTTP restituito dal server. (DOMString)
+
+* **intestazioni**: intestazioni di risposta HTTP dal server. (Oggetto)
+
+ * Attualmente supportato solo iOS.
+
+### iOS stranezze
+
+* Non supporta `responseCode` o`bytesSent`.
+
+## Scarica
+
+**Parametri**:
+
+* **fonte**: URL del server per scaricare il file, come codificato dal`encodeURI()`.
+
+* **destinazione**: Filesystem url che rappresenta il file nel dispositivo. Per indietro la compatibilità, questo può anche essere il percorso completo del file sul dispositivo. (Vedere [indietro compatibilità rileva] qui sotto)
+
+* **successCallback**: un callback passato un `FileEntry` oggetto. *(Funzione)*
+
+* **errorCallback**: un callback che viene eseguito se si verifica un errore durante il recupero `FileEntry`. Richiamato con un oggetto `FileTransferError`. *(Function)*
+
+* **trustAllHosts**: parametro opzionale, valore predefinito è `false` . Se impostata su `true` , accetta tutti i certificati di sicurezza. Questo è utile perché Android respinge i certificati autofirmati sicurezza. Non raccomandato per uso in produzione. Supportato su Android e iOS. *(boolean)*
+
+* **opzioni**: parametri facoltativi, attualmente solo supporti intestazioni (ad esempio autorizzazione (autenticazione di base), ecc.).
+
+### Esempio
+
+ // !! 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
+
+Interrompe un trasferimento in corso. Il callback onerror viene passato un oggetto FileTransferError che presenta un codice di errore di FileTransferError.ABORT_ERR.
+
+### Esempio
+
+ // !! 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
+
+Un oggetto `FileTransferError` viene passato a un callback di errore quando si verifica un errore.
+
+### Proprietà
+
+* **codice**: uno dei codici di errore predefiniti elencati di seguito. (Numero)
+
+* **fonte**: URL all'origine. (String)
+
+* **destinazione**: URL di destinazione. (String)
+
+* **http_status**: codice di stato HTTP. Questo attributo è disponibile solo quando viene ricevuto un codice di risposta della connessione HTTP. (Numero)
+
+* **body** Corpo della risposta. Questo attributo è disponibile solo quando viene ricevuta una risposta dalla connessione HTTP. (String)
+
+* **exception**: O e.getMessage o e.toString (String)
+
+### Costanti
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Note di compatibilità all'indietro
+
+Versioni precedenti di questo plugin accetterebbe solo dispositivo-assoluto-percorsi di file come origine per upload, o come destinazione per il download. Questi percorsi si sarebbero generalmente di forma
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Per indietro compatibilità, questi percorsi sono ancora accettati, e se l'applicazione ha registrato percorsi come questi in un archivio permanente, quindi possono continuare a essere utilizzato.
+
+Questi percorsi sono stati precedentemente esposti nella proprietà `fullPath` di `FileEntry` e oggetti `DirectoryEntry` restituiti dal File plugin. Nuove versioni del File plugin, tuttavia, non è più espongono questi percorsi a JavaScript.
+
+Se si esegue l'aggiornamento a una nuova (1.0.0 o più recente) versione del File e si hanno precedentemente utilizzato `entry.fullPath` come argomenti per `download()` o `upload()`, quindi sarà necessario cambiare il codice per utilizzare gli URL filesystem invece.
+
+`FileEntry.toURL()` e `DirectoryEntry.toURL()` restituiscono un filesystem URL del modulo
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+che può essere utilizzato al posto del percorso assoluto nei metodi sia `download()` e `upload()`.
diff --git a/plugins/cordova-plugin-file-transfer/doc/ja/README.md b/plugins/cordova-plugin-file-transfer/doc/ja/README.md
new file mode 100644
index 0000000..a8156a2
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/ja/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+プラグインのマニュアル:
+
+このプラグインは、アップロードし、ファイルをダウンロードすることができます。
+
+このプラグインでは、グローバル `FileTransfer`、`FileUploadOptions` コンス トラクターを定義します。
+
+グローバル スコープでは使用できませんまで `deviceready` イベントの後です。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## インストール
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## サポートされているプラットフォーム
+
+ * アマゾン火 OS
+ * アンドロイド
+ * ブラックベリー 10
+ * ブラウザー
+ * Firefox の OS * *
+ * iOS
+ * Windows Phone 7 と 8 *
+ * Windows 8
+ * Windows
+
+\ * * `Onprogress`も`abort()`をサポートしていません。*
+
+\ * * * `Onprogress`をサポートしていません。*
+
+# 出色
+
+`出色`オブジェクトは、HTTP マルチパート POST または PUT 要求を使用してファイルをアップロードし、同様にファイルをダウンロードする方法を提供します。
+
+## プロパティ
+
+ * **onprogress**: と呼ばれる、 `ProgressEvent` データの新しいチャンクが転送されるたびに。*(機能)*
+
+## メソッド
+
+ * **アップロード**: サーバーにファイルを送信します。
+
+ * **ダウンロード**: サーバーからファイルをダウンロードします。
+
+ * **中止**: 進行中の転送を中止します。
+
+## upload
+
+**パラメーター**:
+
+ * **fileURL**: デバイス上のファイルを表すファイルシステム URL。 下位互換性は、このことも、デバイス上のファイルの完全パスであります。 (参照してください [後方互換性メモ] の下)
+
+ * **サーバー**: によって符号化されるように、ファイルを受信するサーバーの URL`encodeURI()`.
+
+ * **successCallback**: `FileUploadResult` オブジェクトが渡されるコールバック。*(機能)*
+
+ * **errorCallback**: エラー `FileUploadResult` を取得するが発生した場合に実行されるコールバック。`FileTransferError` オブジェクトを使って呼び出されます。*(機能)*
+
+ * **オプション**: 省略可能なパラメーター *(オブジェクト)*。有効なキー:
+
+ * **fileKey**: フォーム要素の名前。既定値は `file` です。(,)
+ * **ファイル名**: ファイル名、サーバー上のファイルを保存するときに使用します。既定値は `image.jpg` です。(,)
+ * **httpMethod**: - `を置く` または `POST` のいずれかを使用する HTTP メソッド。デフォルト `のポスト` です。(,)
+ * **mimeType**: アップロードするデータの mime タイプ。`イメージ/jpeg` のデフォルトです。(,)
+ * **params**: HTTP リクエストに渡すために任意のキー/値ペアのセット。(オブジェクト)
+ * **chunkedMode**: チャンク ストリーミング モードでデータをアップロードするかどうか。デフォルトは `true` です。(ブール値)
+ * **headers**: ヘッダー名/ヘッダー値のマップ。 配列を使用して、1 つ以上の値を指定します。 IOS、FireOS、アンドロイドではという名前のコンテンツ タイプ ヘッダーが存在する場合、マルチパート フォーム データは使用されません。 (Object)
+ * **httpMethod**: 例えばを使用する HTTP メソッドを POST または PUT です。 デフォルト`のポスト`です。(DOMString)
+
+ * **trustAllHosts**: 省略可能なパラメーターは、デフォルト `false` 。 場合設定 `true` 、セキュリティ証明書をすべて受け付けます。 これは Android の自己署名入りセキュリティ証明書を拒否するので便利です。 運用環境で使用しないでください。 Android と iOS でサポートされています。 *(ブール値)*
+
+### 例
+
+ // !! 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);
+
+
+### サンプルのアップロード ヘッダーと進行状況のイベント (Android と iOS のみ)
+
+ 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
+
+`FileUploadResult` オブジェクトは `FileTransfer` オブジェクト `upload()` メソッドの成功時のコールバックに渡されます。
+
+### プロパティ
+
+ * **bytesSent**: アップロードの一部としてサーバーに送信されたバイト数。(ロング)
+
+ * **記述**: サーバーによって返される HTTP 応答コード。(ロング)
+
+ * **応答**: サーバーによって返される HTTP 応答。(,)
+
+ * **ヘッダー**: HTTP 応答ヘッダー サーバーによって。(オブジェクト)
+
+ * 現在 iOS のみでサポートされます。
+
+### iOS の癖
+
+ * サポートしていない `responseCode` または`bytesSent`.
+
+## download
+
+**パラメーター**:
+
+ * **ソース**: によって符号化されるように、ファイルをダウンロードするサーバーの URL`encodeURI()`.
+
+ * **ターゲット**: デバイス上のファイルを表すファイルシステム url。 下位互換性は、このことも、デバイス上のファイルの完全パスであります。 (参照してください [後方互換性メモ] の下)
+
+ * **successCallback**: 渡されたコールバックを `FileEntry` オブジェクト。*(機能)*
+
+ * **errorCallback**: `FileEntry` を取得するときにエラーが発生した場合に実行されるコールバック。`FileTransferError` オブジェクトを使って呼び出されます。*(機能)*
+
+ * **trustAllHosts**: 省略可能なパラメーターは、デフォルト `false` 。 場合設定 `true` 、セキュリティ証明書をすべて受け付けます。 Android は、自己署名入りセキュリティ証明書を拒否しますので便利です。 運用環境で使用しないでください。 Android と iOS でサポートされています。 *(ブール値)*
+
+ * **オプション**: 省略可能なパラメーターは、現在サポートするヘッダーのみ (認証 (基本認証) など)。
+
+### 例
+
+ // !! 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 癖
+
+ * ダウンロード要求するネイティブ実装によってキャッシュに格納されています。キャッシュされないように、渡す`以来変更された if`ヘッダー メソッドをダウンロードします。
+
+## abort
+
+進行中の転送を中止します。Onerror コールバックが FileTransferError.ABORT_ERR のエラー コードを持っている FileTransferError オブジェクトに渡されます。
+
+### 例
+
+ // !! 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
+
+`FileTransferError` オブジェクトは、エラーが発生したときにエラー コールバックに渡されます。
+
+### プロパティ
+
+ * **コード**: 次のいずれかの定義済みのエラー コード。(数)
+
+ * **ソース**: ソースの URL。(文字列)
+
+ * **ターゲット**: 先の URL。(文字列)
+
+ * **http_status**: HTTP ステータス コード。この属性は、HTTP 接続から応答コードを受信したときにのみ使用できます。(数)
+
+ * **body**応答本体。この属性は、HTTP 接続から応答を受信したときにのみ使用できます。(文字列)
+
+ * **exception**: どちらか e.getMessage または e.toString (文字列)
+
+### 定数
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## 後方互換性をノートします。
+
+このプラグインの以前のバージョンまたはダウンロードのターゲットとして、アップロードのソースとしてのみデバイス絶対ファイル パスを受け入れるでしょう。これらのパスの形式は、通常
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+下位互換性、これらのパスを使用しても、アプリケーションは、永続的なストレージでこのようなパスを記録している場合、し彼らが引き続き使用されます。
+
+これらのパスの `FileEntry` やファイル プラグインによって返される `DirectoryEntry` オブジェクトの `fullPath` プロパティで公開されていなかった。 新しいプラグインのバージョン、ファイル、ただし、もはや java スクリプトの設定をこれらのパスを公開します。
+
+新しいにアップグレードする場合 (1.0.0 以降) ファイルのバージョン以前を使用している `entry.fullPath` `download()` または `upload()` への引数として、ファイルシステムの Url を代わりに使用するコードを変更する必要があります。
+
+`FileEntry.toURL()` と `DirectoryEntry.toURL()` ファイルシステムの URL を返すフォーム
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+`download()`、`upload()` メソッドの絶対ファイル パスの代わりに使用できます。
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file-transfer/doc/ja/index.md b/plugins/cordova-plugin-file-transfer/doc/ja/index.md
new file mode 100644
index 0000000..f885b3c
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/ja/index.md
@@ -0,0 +1,302 @@
+
+
+# cordova-plugin-file-transfer
+
+このプラグインは、アップロードし、ファイルをダウンロードすることができます。
+
+このプラグインでは、グローバル `FileTransfer`、`FileUploadOptions` コンス トラクターを定義します。
+
+グローバル スコープでは使用できませんまで `deviceready` イベントの後です。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## インストール
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## サポートされているプラットフォーム
+
+* アマゾン火 OS
+* アンドロイド
+* ブラックベリー 10
+* ブラウザー
+* Firefox の OS * *
+* iOS
+* Windows Phone 7 と 8 *
+* Windows 8
+* Windows
+
+* *`onprogress` も `abort()` をサポートしていません*
+
+* * *`onprogress` をサポートしていません*
+
+# FileTransfer
+
+`FileTransfer` オブジェクトはマルチパートのポスト、HTTP 要求を使用してファイルをアップロードして同様にファイルをダウンロードする方法を提供します。
+
+## プロパティ
+
+* **onprogress**: と呼ばれる、 `ProgressEvent` データの新しいチャンクが転送されるたびに。*(機能)*
+
+## メソッド
+
+* **アップロード**: サーバーにファイルを送信します。
+
+* **ダウンロード**: サーバーからファイルをダウンロードします。
+
+* **中止**: 進行中の転送を中止します。
+
+## upload
+
+**パラメーター**:
+
+* **fileURL**: デバイス上のファイルを表すファイルシステム URL。 下位互換性は、このことも、デバイス上のファイルの完全パスであります。 (参照してください [後方互換性メモ] の下)
+
+* **サーバー**: によって符号化されるように、ファイルを受信するサーバーの URL`encodeURI()`.
+
+* **successCallback**: `FileUploadResult` オブジェクトが渡されるコールバック。*(機能)*
+
+* **errorCallback**: エラー `FileUploadResult` を取得するが発生した場合に実行されるコールバック。`FileTransferError` オブジェクトを使って呼び出されます。*(機能)*
+
+* **オプション**: 省略可能なパラメーター *(オブジェクト)*。有効なキー:
+
+ * **fileKey**: フォーム要素の名前。既定値は `file` です。(,)
+ * **ファイル名**: ファイル名、サーバー上のファイルを保存するときに使用します。既定値は `image.jpg` です。(,)
+ * **httpMethod**: - `を置く` または `POST` のいずれかを使用する HTTP メソッド。デフォルト `のポスト` です。(,)
+ * **mimeType**: アップロードするデータの mime タイプ。`イメージ/jpeg` のデフォルトです。(,)
+ * **params**: HTTP リクエストに渡すために任意のキー/値ペアのセット。(オブジェクト)
+ * **chunkedMode**: チャンク ストリーミング モードでデータをアップロードするかどうか。デフォルトは `true` です。(ブール値)
+ * **headers**: ヘッダーの名前/ヘッダー値のマップ。1 つ以上の値を指定するには、配列を使用します。(オブジェクト)
+
+* **trustAllHosts**: 省略可能なパラメーターは、デフォルト `false` 。 場合設定 `true` 、セキュリティ証明書をすべて受け付けます。 これは Android の自己署名入りセキュリティ証明書を拒否するので便利です。 運用環境で使用しないでください。 Android と iOS でサポートされています。 *(ブール値)*
+
+### 例
+
+ // !! 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);
+
+
+### サンプルのアップロード ヘッダーと進行状況のイベント (Android と iOS のみ)
+
+ 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
+
+`FileUploadResult` オブジェクトは `FileTransfer` オブジェクト `upload()` メソッドの成功時のコールバックに渡されます。
+
+### プロパティ
+
+* **bytesSent**: アップロードの一部としてサーバーに送信されたバイト数。(ロング)
+
+* **記述**: サーバーによって返される HTTP 応答コード。(ロング)
+
+* **応答**: サーバーによって返される HTTP 応答。(,)
+
+* **ヘッダー**: HTTP 応答ヘッダー サーバーによって。(オブジェクト)
+
+ * 現在 iOS のみでサポートされます。
+
+### iOS の癖
+
+* サポートしていない `responseCode` または`bytesSent`.
+
+## download
+
+**パラメーター**:
+
+* **ソース**: によって符号化されるように、ファイルをダウンロードするサーバーの URL`encodeURI()`.
+
+* **ターゲット**: デバイス上のファイルを表すファイルシステム url。 下位互換性は、このことも、デバイス上のファイルの完全パスであります。 (参照してください [後方互換性メモ] の下)
+
+* **successCallback**: 渡されたコールバックを `FileEntry` オブジェクト。*(機能)*
+
+* **errorCallback**: `FileEntry` を取得するときにエラーが発生した場合に実行されるコールバック。`FileTransferError` オブジェクトを使って呼び出されます。*(機能)*
+
+* **trustAllHosts**: 省略可能なパラメーターは、デフォルト `false` 。 場合設定 `true` 、セキュリティ証明書をすべて受け付けます。 Android は、自己署名入りセキュリティ証明書を拒否しますので便利です。 運用環境で使用しないでください。 Android と iOS でサポートされています。 *(ブール値)*
+
+* **オプション**: 省略可能なパラメーターは、現在サポートするヘッダーのみ (認証 (基本認証) など)。
+
+### 例
+
+ // !! 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
+
+進行中の転送を中止します。Onerror コールバックが FileTransferError.ABORT_ERR のエラー コードを持っている FileTransferError オブジェクトに渡されます。
+
+### 例
+
+ // !! 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
+
+`FileTransferError` オブジェクトは、エラーが発生したときにエラー コールバックに渡されます。
+
+### プロパティ
+
+* **コード**: 次のいずれかの定義済みのエラー コード。(数)
+
+* **ソース**: ソースの URL。(文字列)
+
+* **ターゲット**: 先の URL。(文字列)
+
+* **http_status**: HTTP ステータス コード。この属性は、HTTP 接続から応答コードを受信したときにのみ使用できます。(数)
+
+* **body**応答本体。この属性は、HTTP 接続から応答を受信したときにのみ使用できます。(文字列)
+
+* **exception**: どちらか e.getMessage または e.toString (文字列)
+
+### 定数
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## 後方互換性をノートします。
+
+このプラグインの以前のバージョンまたはダウンロードのターゲットとして、アップロードのソースとしてのみデバイス絶対ファイル パスを受け入れるでしょう。これらのパスの形式は、通常
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+下位互換性、これらのパスを使用しても、アプリケーションは、永続的なストレージでこのようなパスを記録している場合、し彼らが引き続き使用されます。
+
+これらのパスの `FileEntry` やファイル プラグインによって返される `DirectoryEntry` オブジェクトの `fullPath` プロパティで公開されていなかった。 新しいプラグインのバージョン、ファイル、ただし、もはや java スクリプトの設定をこれらのパスを公開します。
+
+新しいにアップグレードする場合 (1.0.0 以降) ファイルのバージョン以前を使用している `entry.fullPath` `download()` または `upload()` への引数として、ファイルシステムの Url を代わりに使用するコードを変更する必要があります。
+
+`FileEntry.toURL()` と `DirectoryEntry.toURL()` ファイルシステムの URL を返すフォーム
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+`download()`、`upload()` メソッドの絶対ファイル パスの代わりに使用できます。
diff --git a/plugins/cordova-plugin-file-transfer/doc/ko/README.md b/plugins/cordova-plugin-file-transfer/doc/ko/README.md
new file mode 100644
index 0000000..f91e8a2
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/ko/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+플러그인 문서:
+
+이 플러그인을 사용 하면 업로드 및 다운로드 파일 수 있습니다.
+
+이 플러그인 글로벌 `FileTransfer`, `FileUploadOptions` 생성자를 정의합니다.
+
+전역 범위에서 그들은 제공 되지 않습니다 때까지 `deviceready` 이벤트 후.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## 설치
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## 지원 되는 플랫폼
+
+ * 아마존 화재 운영 체제
+ * 안 드 로이드
+ * 블랙베리 10
+ * 브라우저
+ * 파이어 폭스 OS * *
+ * iOS
+ * Windows Phone 7과 8 *
+ * 윈도우 8
+ * 윈도우
+
+\** `Onprogress` 도 `abort()` 를 지원 하지 않습니다*
+
+\*** `Onprogress` 를 지원 하지 않습니다*
+
+# FileTransfer
+
+`FileTransfer` 개체는 HTTP 다중 파트 POST 또는 PUT 요청을 사용 하 여 파일을 업로드 하 고 또한 파일을 다운로드 하는 방법을 제공 합니다.
+
+## 속성
+
+ * **onprogress**:로 불리는 `ProgressEvent` 새로운 양의 데이터를 전송 하는 때마다. *(기능)*
+
+## 메서드
+
+ * **업로드**: 파일을 서버에 보냅니다.
+
+ * **다운로드**: 서버에서 파일을 다운로드 합니다.
+
+ * **중단**: 진행 중인 전송 중단.
+
+## 업로드
+
+**매개 변수**:
+
+ * **fileURL**: 장치에 파일을 나타내는 파일 시스템 URL. 에 대 한 이전 버전과 호환성을이 수도 장치에 있는 파일의 전체 경로 수. (참조 [거꾸로 호환성 노트] 아래)
+
+ * **서버**: 인코딩 파일 수신 서버의 URL`encodeURI()`.
+
+ * **successCallback**: `FileUploadResult` 개체를 전달 하는 콜백. *(기능)*
+
+ * **errorCallback**: `FileUploadResult` 검색에 오류가 발생 하면 실행 되는 콜백. `FileTransferError` 개체와 함께 호출 됩니다. *(기능)*
+
+ * **옵션**: 선택적 매개 변수 *(개체)*. 유효한 키:
+
+ * **fileKey**: form 요소의 이름. 기본값은 `file` . (DOMString)
+ * **파일 이름**: 파일 이름을 서버에 파일을 저장할 때 사용 합니다. 기본값은 `image.jpg` . (DOMString)
+ * **httpMethod**: `넣어` 또는 `게시물`-사용 하도록 HTTP 메서드. `게시물` 기본값입니다. (DOMString)
+ * **mimeType**: 업로드 데이터의 mime 형식을. `이미지/jpeg`의 기본값입니다. (DOMString)
+ * **params**: HTTP 요청에 전달할 선택적 키/값 쌍의 집합. (개체)
+ * **chunkedMode**: 청크 스트리밍 모드에서 데이터 업로드를 합니다. 기본값은 `true`입니다. (부울)
+ * **headers**: 헤더 이름 및 헤더 값의 지도. 배열을 사용 하 여 하나 이상의 값을 지정. IOS, FireOS, 안 드 로이드에 있으면 라는 콘텐츠 형식 헤더, 다중 양식 데이터는 사용할 수 없습니다. (Object)
+ * **httpMethod**: HTTP 메서드 예를 사용 하 여 게시 하거나 넣어. `게시물`기본값입니다. (DOMString)
+
+ * **trustAllHosts**: 선택적 매개 변수는 기본적으로 `false` . 만약 설정 `true` , 그것은 모든 보안 인증서를 허용 합니다. 이 안 드 로이드 자체 서명 된 보안 인증서를 거부 하기 때문에 유용 합니다. 프로덕션 환경에서 사용 권장 되지 않습니다. 안 드 로이드와 iOS에서 지원. *(부울)*
+
+### 예를 들어
+
+ // !! 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);
+
+
+### 예를 들어 헤더 업로드 및 진행 이벤트 (안 드 로이드와 iOS만)
+
+ 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
+
+`FileUploadResult` 개체 `FileTransfer` 개체의 `원래` 방법의 성공 콜백에 전달 됩니다.
+
+### 속성
+
+ * **bytesSent**: 업로드의 일부로 서버에 보낸 바이트 수. (긴)
+
+ * **responseCode**: 서버에서 반환 된 HTTP 응답 코드. (긴)
+
+ * **response**: 서버에서 반환 되는 HTTP 응답. (DOMString)
+
+ * **headers**: 서버에서 HTTP 응답 헤더. (개체)
+
+ * 현재 ios만 지원 합니다.
+
+### iOS 단점
+
+ * 지원 하지 않는 `responseCode` 또는`bytesSent`.
+
+## download
+
+**매개 변수**:
+
+ * **source**: URL로 인코딩된 파일, 다운로드 서버`encodeURI()`.
+
+ * **target**: 장치에 파일을 나타내는 파일 시스템 url. 에 대 한 이전 버전과 호환성을이 수도 장치에 있는 파일의 전체 경로 수. (참조 [거꾸로 호환성 노트] 아래)
+
+ * **successCallback**: 콜백 전달 되는 `FileEntry` 개체. *(기능)*
+
+ * **errorCallback**: `FileEntry`를 검색할 때 오류가 발생 하면 실행 되는 콜백. `FileTransferError` 개체와 함께 호출 됩니다. *(기능)*
+
+ * **trustAllHosts**: 선택적 매개 변수는 기본적으로 `false` . 만약 설정 `true` , 그것은 모든 보안 인증서를 허용 합니다. 안 드 로이드 자체 서명 된 보안 인증서를 거부 하기 때문에 유용 합니다. 프로덕션 환경에서 사용 권장 되지 않습니다. 안 드 로이드와 iOS에서 지원. *(부울)*
+
+ * **options**: 선택적 매개 변수를 현재 지 원하는 머리글만 (예: 인증 (기본 인증), 등).
+
+### 예를 들어
+
+ // !! 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 특수
+
+ * 다운로드 요청 기본 구현에 의해 캐시 되 고. 캐싱을 방지 하려면 전달 `if-수정-이후` 헤더를 다운로드 하는 방법.
+
+## abort
+
+진행 중인 전송을 중단합니다. onerror 콜백 FileTransferError.ABORT_ERR의 오류 코드는 FileTransferError 개체를 전달 합니다.
+
+### 예를 들어
+
+ // !! 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
+
+`FileTransferError` 개체 오류가 발생 하면 오류 콜백에 전달 됩니다.
+
+### 속성
+
+ * **code**: 미리 정의 된 오류 코드 중 하나가 아래에 나열 된. (수)
+
+ * **source**: 소스 URL. (문자열)
+
+ * **target**: 대상 URL. (문자열)
+
+ * **http_status**: HTTP 상태 코드. 이 특성은 응답 코드를 HTTP 연결에서 수신에 사용할 수 있습니다. (수)
+
+ * **body** 응답 본문입니다. 이 특성은 HTTP 연결에서 응답을 받을 때에 사용할 수 있습니다. (문자열)
+
+ * **exception**: 어느 e.getMessage 또는 e.toString (문자열)
+
+### 상수
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## 이전 버전과 호환성 노트
+
+이 플러그인의 이전 버전만 업로드에 대 한 소스 또는 다운로드에 대 한 대상 장치 절대 파일 경로 받아들일 것 이다. 이러한 경로 일반적으로 폼의 것
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+대 한 뒤 호환성, 이러한 경로 여전히 허용, 그리고 응용 프로그램이 영구 저장소에서 이와 같은 경로 기록 했다, 그때 그들은 계속할 수 있다면 사용할 수.
+
+이러한 경로 `FileEntry` 및 파일 플러그인에 의해 반환 된 `DirectoryEntry` 개체의 `fullPath` 속성에 노출 되었던. 그러나 파일 플러그인의,, 더 이상 새로운 버전 자바 스크립트이 경로 노출.
+
+새로 업그레이드 하는 경우 (1.0.0 이상) 버전의 파일, 및 이전 사용 하 고 `entry.fullPath` `download()` 또는 `upload()` 인수로 다음 대신 파일 시스템 Url을 사용 하 여 코드를 변경 해야 합니다.
+
+폼의 파일 URL을 반환 하는 `FileEntry.toURL()` 및 `DirectoryEntry.toURL()`
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+어떤 `download()` 및 `upload()` 방법에서 절대 파일 경로 대신 사용할 수 있습니다.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file-transfer/doc/ko/index.md b/plugins/cordova-plugin-file-transfer/doc/ko/index.md
new file mode 100644
index 0000000..a6e39c0
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/ko/index.md
@@ -0,0 +1,302 @@
+
+
+# cordova-plugin-file-transfer
+
+이 플러그인을 사용 하면 업로드 및 다운로드 파일 수 있습니다.
+
+이 플러그인 글로벌 `FileTransfer`, `FileUploadOptions` 생성자를 정의합니다.
+
+전역 범위에서 그들은 제공 되지 않습니다 때까지 `deviceready` 이벤트 후.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## 설치
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## 지원 되는 플랫폼
+
+* 아마존 화재 운영 체제
+* 안 드 로이드
+* 블랙베리 10
+* 브라우저
+* 파이어 폭스 OS * *
+* iOS
+* Windows Phone 7과 8 *
+* 윈도우 8
+* 윈도우
+
+* *`onprogress`도 `abort()`를 지원 하지 않습니다*
+
+* * *`onprogress`를 지원 하지 않습니다*
+
+# FileTransfer
+
+`FileTransfer` 개체는 HTTP 다중 파트 POST 요청을 사용 하 여 파일 업로드 뿐만 아니라 파일을 다운로드 하는 방법을 제공 합니다.
+
+## 속성
+
+* **onprogress**:로 불리는 `ProgressEvent` 새로운 양의 데이터를 전송 하는 때마다. *(기능)*
+
+## 메서드
+
+* **업로드**: 파일을 서버에 보냅니다.
+
+* **다운로드**: 서버에서 파일을 다운로드 합니다.
+
+* **중단**: 진행 중인 전송 중단.
+
+## 업로드
+
+**매개 변수**:
+
+* **fileURL**: 장치에 파일을 나타내는 파일 시스템 URL. 에 대 한 이전 버전과 호환성을이 수도 장치에 있는 파일의 전체 경로 수. (참조 [거꾸로 호환성 노트] 아래)
+
+* **서버**: 인코딩 파일 수신 서버의 URL`encodeURI()`.
+
+* **successCallback**: `FileUploadResult` 개체를 전달 하는 콜백. *(기능)*
+
+* **errorCallback**: `FileUploadResult` 검색에 오류가 발생 하면 실행 되는 콜백. `FileTransferError` 개체와 함께 호출 됩니다. *(기능)*
+
+* **옵션**: 선택적 매개 변수 *(개체)*. 유효한 키:
+
+ * **fileKey**: form 요소의 이름. 기본값은 `file` . (DOMString)
+ * **파일 이름**: 파일 이름을 서버에 파일을 저장할 때 사용 합니다. 기본값은 `image.jpg` . (DOMString)
+ * **httpMethod**: `넣어` 또는 `게시물`-사용 하도록 HTTP 메서드. `게시물` 기본값입니다. (DOMString)
+ * **mimeType**: 업로드 데이터의 mime 형식을. `이미지/jpeg`의 기본값입니다. (DOMString)
+ * **params**: HTTP 요청에 전달할 선택적 키/값 쌍의 집합. (개체)
+ * **chunkedMode**: 청크 스트리밍 모드에서 데이터 업로드를 합니다. 기본값은 `true`입니다. (부울)
+ * **headers**: 헤더 이름/헤더 값의 지도. 배열을 사용 하 여 하나 이상의 값을 지정 합니다. (개체)
+
+* **trustAllHosts**: 선택적 매개 변수는 기본적으로 `false` . 만약 설정 `true` , 그것은 모든 보안 인증서를 허용 합니다. 이 안 드 로이드 자체 서명 된 보안 인증서를 거부 하기 때문에 유용 합니다. 프로덕션 환경에서 사용 권장 되지 않습니다. 안 드 로이드와 iOS에서 지원. *(부울)*
+
+### 예를 들어
+
+ // !! 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);
+
+
+### 예를 들어 헤더 업로드 및 진행 이벤트 (안 드 로이드와 iOS만)
+
+ 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
+
+`FileUploadResult` 개체 `FileTransfer` 개체의 `원래` 방법의 성공 콜백에 전달 됩니다.
+
+### 속성
+
+* **bytesSent**: 업로드의 일부로 서버에 보낸 바이트 수. (긴)
+
+* **responseCode**: 서버에서 반환 된 HTTP 응답 코드. (긴)
+
+* **response**: 서버에서 반환 되는 HTTP 응답. (DOMString)
+
+* **headers**: 서버에서 HTTP 응답 헤더. (개체)
+
+ * 현재 ios만 지원 합니다.
+
+### iOS 단점
+
+* 지원 하지 않는 `responseCode` 또는`bytesSent`.
+
+## download
+
+**매개 변수**:
+
+* **source**: URL로 인코딩된 파일, 다운로드 서버`encodeURI()`.
+
+* **target**: 장치에 파일을 나타내는 파일 시스템 url. 에 대 한 이전 버전과 호환성을이 수도 장치에 있는 파일의 전체 경로 수. (참조 [거꾸로 호환성 노트] 아래)
+
+* **successCallback**: 콜백 전달 되는 `FileEntry` 개체. *(기능)*
+
+* **errorCallback**: `FileEntry`를 검색할 때 오류가 발생 하면 실행 되는 콜백. `FileTransferError` 개체와 함께 호출 됩니다. *(기능)*
+
+* **trustAllHosts**: 선택적 매개 변수는 기본적으로 `false` . 만약 설정 `true` , 그것은 모든 보안 인증서를 허용 합니다. 안 드 로이드 자체 서명 된 보안 인증서를 거부 하기 때문에 유용 합니다. 프로덕션 환경에서 사용 권장 되지 않습니다. 안 드 로이드와 iOS에서 지원. *(부울)*
+
+* **options**: 선택적 매개 변수를 현재 지 원하는 머리글만 (예: 인증 (기본 인증), 등).
+
+### 예를 들어
+
+ // !! 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
+
+진행 중인 전송을 중단합니다. onerror 콜백 FileTransferError.ABORT_ERR의 오류 코드는 FileTransferError 개체를 전달 합니다.
+
+### 예를 들어
+
+ // !! 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
+
+`FileTransferError` 개체 오류가 발생 하면 오류 콜백에 전달 됩니다.
+
+### 속성
+
+* **code**: 미리 정의 된 오류 코드 중 하나가 아래에 나열 된. (수)
+
+* **source**: 소스 URL. (문자열)
+
+* **target**: 대상 URL. (문자열)
+
+* **http_status**: HTTP 상태 코드. 이 특성은 응답 코드를 HTTP 연결에서 수신에 사용할 수 있습니다. (수)
+
+* **body** 응답 본문입니다. 이 특성은 HTTP 연결에서 응답을 받을 때에 사용할 수 있습니다. (문자열)
+
+* **exception**: 어느 e.getMessage 또는 e.toString (문자열)
+
+### 상수
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## 이전 버전과 호환성 노트
+
+이 플러그인의 이전 버전만 업로드에 대 한 소스 또는 다운로드에 대 한 대상 장치 절대 파일 경로 받아들일 것 이다. 이러한 경로 일반적으로 폼의 것
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+대 한 뒤 호환성, 이러한 경로 여전히 허용, 그리고 응용 프로그램이 영구 저장소에서 이와 같은 경로 기록 했다, 그때 그들은 계속할 수 있다면 사용할 수.
+
+이러한 경로 `FileEntry` 및 파일 플러그인에 의해 반환 된 `DirectoryEntry` 개체의 `fullPath` 속성에 노출 되었던. 그러나 파일 플러그인의,, 더 이상 새로운 버전 자바 스크립트이 경로 노출.
+
+새로 업그레이드 하는 경우 (1.0.0 이상) 버전의 파일, 및 이전 사용 하 고 `entry.fullPath` `download()` 또는 `upload()` 인수로 다음 대신 파일 시스템 Url을 사용 하 여 코드를 변경 해야 합니다.
+
+폼의 파일 URL을 반환 하는 `FileEntry.toURL()` 및 `DirectoryEntry.toURL()`
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+어떤 `download()` 및 `upload()` 방법에서 절대 파일 경로 대신 사용할 수 있습니다.
diff --git a/plugins/cordova-plugin-file-transfer/doc/pl/README.md b/plugins/cordova-plugin-file-transfer/doc/pl/README.md
new file mode 100644
index 0000000..c430979
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/pl/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+Plugin dokumentacja:
+
+Plugin pozwala na przesyłanie i pobieranie plików.
+
+Ten plugin określa globalne `FileTransfer`, `FileUploadOptions` konstruktorów.
+
+Chociaż w globalnym zasięgu, są nie dostępne dopiero po `deviceready` imprezie.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Instalacja
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Obsługiwane platformy
+
+ * Amazon Fire OS
+ * Android
+ * BlackBerry 10
+ * Przeglądarka
+ * Firefox OS **
+ * iOS
+ * Windows Phone 7 i 8 *
+ * Windows 8
+ * Windows
+
+\ * *Nie obsługują `onprogress` ani `abort()` *
+
+\ ** *Nie obsługują `onprogress` *
+
+# FileTransfer
+
+Obiekt `FileTransfer` zapewnia sposób wgrać pliki za pomocą Multi-część POST lub PUT żądania HTTP i pobierania plików, jak również.
+
+## Właściwości
+
+ * **OnProgress**: o nazwie `ProgressEvent` gdy nowy kawałek danych jest przenoszona. *(Funkcja)*
+
+## Metody
+
+ * **wgraj**: wysyła plik na serwer.
+
+ * **do pobrania**: pliki do pobrania pliku z serwera.
+
+ * **przerwać**: przerywa w toku transferu.
+
+## upload
+
+**Parametry**:
+
+ * **fileURL**: URL plików reprezentujących pliku na urządzenie. Dla wstecznej kompatybilności, to może również być pełną ścieżkę pliku na urządzenie. (Zobacz [wstecz zgodności zauważa] poniżej)
+
+ * **serwer**: adres URL serwera, aby otrzymać plik, jak kodowane przez`encodeURI()`.
+
+ * **successCallback**: wywołania zwrotnego, który jest przekazywany obiekt `FileUploadResult`. *(Funkcja)*
+
+ * **errorCallback**: wywołanie zwrotne, które wykonuje, jeżeli wystąpi błąd pobierania `FileUploadResult`. Wywoływany z obiektu `FileTransferError`. *(Funkcja)*
+
+ * **Opcje**: parametry opcjonalne *(obiektu)*. Ważne klucze:
+
+ * **fileKey**: nazwa elementu form. Domyślnie `file` . (DOMString)
+ * **Nazwa pliku**: nazwy pliku, aby użyć podczas zapisywania pliku na serwerze. Domyślnie `image.jpg` . (DOMString)
+ * **element httpMethod**: Metoda HTTP do użycia - `umieścić` lub `POST`. Domyślnie `POST`. (DOMString)
+ * **mimeType**: Typ mime danych do przesłania. Domyślnie do `image/jpeg`. (DOMString)
+ * **params**: zestaw par opcjonalny klucz/wartość w żądaniu HTTP. (Obiekt)
+ * **chunkedMode**: czy przekazać dane w trybie pakietowego przesyłania strumieniowego. Wartością domyślną jest `true`. (Wartość logiczna)
+ * **headers**: Mapa wartości Nazwa/nagłówka nagłówek. Aby określić więcej niż jedną wartość, należy użyć tablicę. Na iOS, FireOS i Android jeśli nagłówek o nazwie Content-Type jest obecny, wieloczęściowa forma nie danych. (Object)
+ * **element httpMethod**: Metoda HTTP np. POST lub PUT. Ustawienia domyślne do `POST`. (DOMString)
+
+ * **trustAllHosts**: parametr opcjonalny, domyślnie `false` . Jeśli zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeństwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca się do użytku produkcyjnego. Obsługiwane na Androida i iOS. *(wartość logiczna)*
+
+### Przykład
+
+ // !! 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);
+
+
+### Przykład z Prześlij nagłówki i zdarzeń postępu (Android i iOS tylko)
+
+ 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
+
+Obiekt `FileUploadResult` jest przekazywana do sukcesu wywołania zwrotnego metody `upload() służącą` obiektu `FileTransfer`.
+
+### Właściwości
+
+ * **bytesSent**: liczba bajtów wysłanych do serwera jako część upload. (długie)
+
+ * **responseCode**: kod odpowiedzi HTTP, zwracane przez serwer. (długie)
+
+ * **odpowiedź**: HTTP odpowiedzi zwracane przez serwer. (DOMString)
+
+ * **nagłówki**: nagłówki HTTP odpowiedzi przez serwer. (Obiekt)
+
+ * Obecnie obsługiwane na iOS tylko.
+
+### Dziwactwa iOS
+
+ * Nie obsługuje `responseCode` lub`bytesSent`.
+
+## download
+
+**Parametry**:
+
+ * **Źródło**: adres URL serwera, aby pobrać plik, jak kodowane przez`encodeURI()`.
+
+ * **cel**: url plików reprezentujących pliku na urządzenie. Dla wstecznej kompatybilności, to może również być pełną ścieżkę pliku na urządzenie. (Zobacz [wstecz zgodności zauważa] poniżej)
+
+ * **successCallback**: wywołania zwrotnego, który jest przekazywany `FileEntry` obiektu. *(Funkcja)*
+
+ * **errorCallback**: wywołanie zwrotne, które wykonuje, jeśli wystąpi błąd podczas pobierania `FileEntry`. Wywoływany z obiektu `FileTransferError`. *(Funkcja)*
+
+ * **trustAllHosts**: parametr opcjonalny, domyślnie `false` . Jeśli zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeństwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca się do użytku produkcyjnego. Obsługiwane na Androida i iOS. *(wartość logiczna)*
+
+ * **Opcje**: parametry opcjonalne, obecnie tylko obsługuje nagłówki (takie jak autoryzacja (uwierzytelnianie podstawowe), itp.).
+
+### Przykład
+
+ // !! 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 dziwactwa
+
+ * Pobierz wnioski są buforowane przez rodzimych realizacji. Aby uniknąć, buforowanie, przekazać `if-Modified-Since` nagłówka do pobrania Metoda.
+
+## abort
+
+Przerywa w toku transferu. Onerror callback jest przekazywany obiekt FileTransferError, który kod błędu z FileTransferError.ABORT_ERR.
+
+### Przykład
+
+ // !! 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
+
+Obiekt `FileTransferError` jest przekazywana do błąd wywołania zwrotnego, gdy wystąpi błąd.
+
+### Właściwości
+
+ * **Kod**: jeden z kodów błędów wstępnie zdefiniowanych poniżej. (Liczba)
+
+ * **Źródło**: URL do źródła. (String)
+
+ * **cel**: adres URL do docelowego. (String)
+
+ * **HTTP_STATUS**: kod stanu HTTP. Ten atrybut jest dostępna tylko po otrzymaniu kodu odpowiedzi z połączenia HTTP. (Liczba)
+
+ * **body** Treść odpowiedzi. Ten atrybut jest dostępna tylko wtedy, gdy odpowiedź jest otrzymanych od połączenia HTTP. (String)
+
+ * **exception**: albo e.getMessage lub e.toString (String)
+
+### Stałe
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Do tyłu zgodności stwierdza
+
+Poprzednie wersje tego pluginu tylko zaakceptować urządzenia bezwzględnych ścieżek jako źródło dla przekazywania, lub w celu pobrania. Te ścieżki będzie zazwyczaj formy
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Do tyłu zgodności, akceptowane są jeszcze te ścieżki, i jeśli aplikacja nagrał ścieżki, jak te w trwałej pamięci, następnie można nadal stosować.
+
+Te ścieżki były narażone wcześniej we właściwości `fullPath` `FileEntry` i `DirectoryEntry` obiektów zwróconych przez wtyczki pliku. Nowe wersje pliku plugin, jednak już wystawiać te ścieżki do JavaScript.
+
+Jeśli uaktualniasz nowy (1.0.0 lub nowsza) wersja pliku i mieć wcześniej przy `entry.fullPath` jako argumenty `download()` lub `upload() służącą`, a następnie trzeba będzie zmienić kod aby używać adresów URL plików zamiast.
+
+`FileEntry.toURL()` i `DirectoryEntry.toURL()` zwraca adres URL plików formularza
+
+ 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
diff --git a/plugins/cordova-plugin-file-transfer/doc/pl/index.md b/plugins/cordova-plugin-file-transfer/doc/pl/index.md
new file mode 100644
index 0000000..ff9b557
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/pl/index.md
@@ -0,0 +1,302 @@
+
+
+# cordova-plugin-file-transfer
+
+Plugin pozwala na przesyłanie i pobieranie plików.
+
+Ten plugin określa globalne `FileTransfer`, `FileUploadOptions` konstruktorów.
+
+Chociaż w globalnym zasięgu, są nie dostępne dopiero po `deviceready` imprezie.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## Instalacja
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Obsługiwane platformy
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Przeglądarka
+* Firefox OS **
+* iOS
+* Windows Phone 7 i 8 *
+* Windows 8
+* Windows
+
+* *Nie obsługują `onprogress` ani `abort()`*
+
+* * *Nie obsługują `onprogress`*
+
+# FileTransfer
+
+Obiekt `FileTransfer` zapewnia sposób wgrać pliki przy użyciu żądania HTTP wieloczęściowe POST i pobierania plików, jak również.
+
+## Właściwości
+
+* **OnProgress**: o nazwie `ProgressEvent` gdy nowy kawałek danych jest przenoszona. *(Funkcja)*
+
+## Metody
+
+* **wgraj**: wysyła plik na serwer.
+
+* **do pobrania**: pliki do pobrania pliku z serwera.
+
+* **przerwać**: przerywa w toku transferu.
+
+## upload
+
+**Parametry**:
+
+* **fileURL**: URL plików reprezentujących pliku na urządzenie. Dla wstecznej kompatybilności, to może również być pełną ścieżkę pliku na urządzenie. (Zobacz [wstecz zgodności zauważa] poniżej)
+
+* **serwer**: adres URL serwera, aby otrzymać plik, jak kodowane przez`encodeURI()`.
+
+* **successCallback**: wywołania zwrotnego, który jest przekazywany obiekt `FileUploadResult`. *(Funkcja)*
+
+* **errorCallback**: wywołanie zwrotne, które wykonuje, jeżeli wystąpi błąd pobierania `FileUploadResult`. Wywoływany z obiektu `FileTransferError`. *(Funkcja)*
+
+* **Opcje**: parametry opcjonalne *(obiektu)*. Ważne klucze:
+
+ * **fileKey**: nazwa elementu form. Domyślnie `file` . (DOMString)
+ * **Nazwa pliku**: nazwy pliku, aby użyć podczas zapisywania pliku na serwerze. Domyślnie `image.jpg` . (DOMString)
+ * **element httpMethod**: Metoda HTTP do użycia - `umieścić` lub `POST`. Domyślnie `POST`. (DOMString)
+ * **mimeType**: Typ mime danych do przesłania. Domyślnie do `image/jpeg`. (DOMString)
+ * **params**: zestaw par opcjonalny klucz/wartość w żądaniu HTTP. (Obiekt)
+ * **chunkedMode**: czy przekazać dane w trybie pakietowego przesyłania strumieniowego. Wartością domyślną jest `true`. (Wartość logiczna)
+ * **headers**: Mapa wartości Nazwa/nagłówka nagłówek. Aby określić więcej niż jedną wartość, należy użyć tablicę. (Obiekt)
+
+* **trustAllHosts**: parametr opcjonalny, domyślnie `false` . Jeśli zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeństwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca się do użytku produkcyjnego. Obsługiwane na Androida i iOS. *(wartość logiczna)*
+
+### Przykład
+
+ // !! 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);
+
+
+### Przykład z Prześlij nagłówki i zdarzeń postępu (Android i iOS tylko)
+
+ 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
+
+Obiekt `FileUploadResult` jest przekazywana do sukcesu wywołania zwrotnego metody `upload() służącą` obiektu `FileTransfer`.
+
+### Właściwości
+
+* **bytesSent**: liczba bajtów wysłanych do serwera jako część upload. (długie)
+
+* **responseCode**: kod odpowiedzi HTTP, zwracane przez serwer. (długie)
+
+* **odpowiedź**: HTTP odpowiedzi zwracane przez serwer. (DOMString)
+
+* **nagłówki**: nagłówki HTTP odpowiedzi przez serwer. (Obiekt)
+
+ * Obecnie obsługiwane na iOS tylko.
+
+### Dziwactwa iOS
+
+* Nie obsługuje `responseCode` lub`bytesSent`.
+
+## download
+
+**Parametry**:
+
+* **Źródło**: adres URL serwera, aby pobrać plik, jak kodowane przez`encodeURI()`.
+
+* **cel**: url plików reprezentujących pliku na urządzenie. Dla wstecznej kompatybilności, to może również być pełną ścieżkę pliku na urządzenie. (Zobacz [wstecz zgodności zauważa] poniżej)
+
+* **successCallback**: wywołania zwrotnego, który jest przekazywany `FileEntry` obiektu. *(Funkcja)*
+
+* **errorCallback**: wywołanie zwrotne, które wykonuje, jeśli wystąpi błąd podczas pobierania `FileEntry`. Wywoływany z obiektu `FileTransferError`. *(Funkcja)*
+
+* **trustAllHosts**: parametr opcjonalny, domyślnie `false` . Jeśli zestaw `true` , to akceptuje wszystkie certyfikaty bezpieczeństwa. Jest to przydatne, ponieważ Android odrzuca Certyfikaty samopodpisane. Nie zaleca się do użytku produkcyjnego. Obsługiwane na Androida i iOS. *(wartość logiczna)*
+
+* **Opcje**: parametry opcjonalne, obecnie tylko obsługuje nagłówki (takie jak autoryzacja (uwierzytelnianie podstawowe), itp.).
+
+### Przykład
+
+ // !! 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
+
+Przerywa w toku transferu. Onerror callback jest przekazywany obiekt FileTransferError, który kod błędu z FileTransferError.ABORT_ERR.
+
+### Przykład
+
+ // !! 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
+
+Obiekt `FileTransferError` jest przekazywana do błąd wywołania zwrotnego, gdy wystąpi błąd.
+
+### Właściwości
+
+* **Kod**: jeden z kodów błędów wstępnie zdefiniowanych poniżej. (Liczba)
+
+* **Źródło**: URL do źródła. (String)
+
+* **cel**: adres URL do docelowego. (String)
+
+* **HTTP_STATUS**: kod stanu HTTP. Ten atrybut jest dostępna tylko po otrzymaniu kodu odpowiedzi z połączenia HTTP. (Liczba)
+
+* **body** Treść odpowiedzi. Ten atrybut jest dostępna tylko wtedy, gdy odpowiedź jest otrzymanych od połączenia HTTP. (String)
+
+* **exception**: albo e.getMessage lub e.toString (String)
+
+### Stałe
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Do tyłu zgodności stwierdza
+
+Poprzednie wersje tego pluginu tylko zaakceptować urządzenia bezwzględnych ścieżek jako źródło dla przekazywania, lub w celu pobrania. Te ścieżki będzie zazwyczaj formy
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Do tyłu zgodności, akceptowane są jeszcze te ścieżki, i jeśli aplikacja nagrał ścieżki, jak te w trwałej pamięci, następnie można nadal stosować.
+
+Te ścieżki były narażone wcześniej we właściwości `fullPath` `FileEntry` i `DirectoryEntry` obiektów zwróconych przez wtyczki pliku. Nowe wersje pliku plugin, jednak już wystawiać te ścieżki do JavaScript.
+
+Jeśli uaktualniasz nowy (1.0.0 lub nowsza) wersja pliku i mieć wcześniej przy `entry.fullPath` jako argumenty `download()` lub `upload() służącą`, a następnie trzeba będzie zmienić kod aby używać adresów URL plików zamiast.
+
+`FileEntry.toURL()` i `DirectoryEntry.toURL()` zwraca adres URL plików formularza
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+które mogą być używane zamiast bezwzględna ścieżka zarówno `download()` i `metody upload()` metody.
diff --git a/plugins/cordova-plugin-file-transfer/doc/ru/index.md b/plugins/cordova-plugin-file-transfer/doc/ru/index.md
new file mode 100644
index 0000000..cdd5a15
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/ru/index.md
@@ -0,0 +1,290 @@
+
+
+# cordova-plugin-file-transfer
+
+Этот плагин позволяет вам загружать и скачивать файлы.
+
+## Установка
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## Поддерживаемые платформы
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Firefox OS **
+* iOS
+* Windows Phone 7 и 8 *
+* Windows 8 ***|
+* Windows ***|
+
+* *Не поддерживают `onprogress` , ни `abort()` *
+
+** *Не поддерживает `onprogress` *
+
+Частичная поддержка `onprogress` для закачки метод. `onprogress` вызывается с пустой ход событий благодаря Windows limitations_
+
+# FileTransfer
+
+`FileTransfer`Объект предоставляет способ для загрузки файлов с помощью нескольких частей запроса POST HTTP и для загрузки файлов, а также.
+
+## Параметры
+
+* **OnProgress**: называется с `ProgressEvent` всякий раз, когда новый фрагмент данных передается. *(Функция)*
+
+## Методы
+
+* **добавлено**: отправляет файл на сервер.
+
+* **скачать**: Скачать файл с сервера.
+
+* **прервать**: прерывает передачу в прогресс.
+
+## загрузить
+
+**Параметры**:
+
+* **fileURL**: файловой системы URL-адрес, представляющий файл на устройстве. Для обратной совместимости, это также может быть полный путь к файлу на устройстве. (См. [обратной совместимости отмечает] ниже)
+
+* **сервер**: URL-адрес сервера, чтобы получить файл, как закодированные`encodeURI()`.
+
+* **successCallback**: обратного вызова, передаваемого `Metadata` объект. *(Функция)*
+
+* **errorCallback**: обратного вызова, который выполняется в случае получения ошибки `Metadata` . Вызываемый с `FileTransferError` объект. *(Функция)*
+
+* **опции**: необязательные параметры *(объект)*. Допустимые ключи:
+
+ * **fileKey**: имя элемента form. По умолчанию `file` . (DOMString)
+ * **имя файла**: имя файла для использования при сохранении файла на сервере. По умолчанию `image.jpg` . (DOMString)
+ * **mimeType**: mime-тип данных для загрузки. По умолчанию `image/jpeg` . (DOMString)
+ * **params**: набор пар дополнительный ключ/значение для передачи в HTTP-запросе. (Объект)
+ * **chunkedMode**: следует ли загружать данные в фрагментарности потоковом режиме. По умолчанию `true` . (Логическое значение)
+ * **заголовки**: Карта значений заголовок имя заголовка. Используйте массив для указания более одного значения. (Объект)
+
+* **trustAllHosts**: необязательный параметр, по умолчанию `false` . Если значение `true` , она принимает все сертификаты безопасности. Это полезно, поскольку Android отвергает самозаверяющие сертификаты. Не рекомендуется для использования в производстве. Поддерживается на Android и iOS. *(логическое значение)*
+
+### Пример
+
+ // !! 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);
+
+
+### Пример с загружать заголовки и события Progress (Android и iOS только)
+
+ 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
+
+Объект `FileUploadResult` передается на успех обратного вызова метода `upload()` объекта `FileTransfer`.
+
+### Параметры
+
+* **bytesSent**: количество байт, отправленных на сервер как часть загрузки. (длинная)
+
+* **responseCode**: код ответа HTTP, возвращаемых сервером. (длинная)
+
+* **ответ**: ответ HTTP, возвращаемых сервером. (DOMString)
+
+* **заголовки**: заголовки ответов HTTP-сервером. (Объект)
+
+ * В настоящее время поддерживается только для iOS.
+
+### Особенности iOS
+
+* Не поддерживает `responseCode` или`bytesSent`.
+
+## Скачать
+
+**Параметры**:
+
+* **источник**: URL-адрес сервера для загрузки файла, как закодированные`encodeURI()`.
+
+* **Цель**: файловой системы URL-адрес, представляющий файл на устройстве. Для обратной совместимости, это также может быть полный путь к файлу на устройстве. (См. [обратной совместимости отмечает] ниже)
+
+* **successCallback**: обратного вызова, передаваемого `FileEntry` объект. *(Функция)*
+
+* **errorCallback**: обратного вызова, который выполняется, если возникает ошибка при получении `Metadata` . Вызываемый с `FileTransferError` объект. *(Функция)*
+
+* **trustAllHosts**: необязательный параметр, по умолчанию `false` . Если значение `true` , она принимает все сертификаты безопасности. Это полезно, потому что Android отвергает самозаверяющие сертификаты. Не рекомендуется для использования в производстве. Поддерживается на Android и iOS. *(логическое значение)*
+
+* **опции**: необязательные параметры, в настоящее время только поддерживает заголовки (например авторизации (базовая аутентификация) и т.д.).
+
+### Пример
+
+ // !! 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=="
+ }
+ }
+ );
+
+
+## прервать
+
+Прерывает передачу в прогресс. Onerror обратного вызова передается объект FileTransferError, который имеет код ошибки FileTransferError.ABORT_ERR.
+
+### Пример
+
+ // !! 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` при ошибке обратного вызова передается объект, при возникновении ошибки.
+
+### Параметры
+
+* **код**: один из кодов стандартных ошибок, перечисленные ниже. (Число)
+
+* **источник**: URL-адрес источника. (Строка)
+
+* **Цель**: URL-адрес к целевому объекту. (Строка)
+
+* **http_status**: код состояния HTTP. Этот атрибут доступен только при код ответа от HTTP-соединения. (Число)
+
+* **исключение**: либо e.getMessage или e.toString (строка)
+
+### Константы
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## Обратной совместимости отмечает
+
+Предыдущие версии этого плагина будет принимать только устройства Абсолют файлам как источник для закачки, или как целевых для загрузок. Обычно эти пути бы формы
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Для обратной совместимости, по-прежнему принимаются эти пути, и если ваше приложение зарегистрировано пути как в постоянное хранилище, то они могут продолжать использоваться.
+
+Эти пути ранее были видны в `fullPath` свойства `FileEntry` и `DirectoryEntry` объекты, возвращаемые файл плагина. Новые версии файла плагина, однако, не подвергать эти пути в JavaScript.
+
+Если вы переходите на новый (1.0.0 или новее) версию файла и вы ранее использовали `entry.fullPath` в качестве аргументов `download()` или `upload()` , то вам необходимо будет изменить код для использования файловой системы URL вместо.
+
+`FileEntry.toURL()`и `DirectoryEntry.toURL()` возвращает URL-адрес формы файловой системы
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+которые могут быть использованы вместо абсолютного пути в обоих `download()` и `upload()` методы.
diff --git a/plugins/cordova-plugin-file-transfer/doc/zh/README.md b/plugins/cordova-plugin-file-transfer/doc/zh/README.md
new file mode 100644
index 0000000..5399b04
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/zh/README.md
@@ -0,0 +1,311 @@
+
+
+# cordova-plugin-file-transfer
+
+[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
+
+外掛程式檔:
+
+這個外掛程式允許你上傳和下載檔案。
+
+這個外掛程式定義全域 `FileTransfer`,`FileUploadOptions` 的建構函式。
+
+雖然在全球範圍內,他們不可用直到 `deviceready` 事件之後。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## 安裝
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## 支援的平臺
+
+ * 亞馬遜火 OS
+ * Android 系統
+ * 黑莓 10
+ * 瀏覽器
+ * 火狐瀏覽器的作業系統 * *
+ * iOS
+ * Windows Phone 7 和 8 *
+ * Windows 8
+ * Windows
+
+\ **不支援`onprogress`也`abort()` *
+
+\ * **不支援`onprogress` *
+
+# 檔案傳輸
+
+`FileTransfer`物件提供上傳檔使用 HTTP 多部分職位或付諸表決的請求,並將檔以及下載的方式。
+
+## 屬性
+
+ * **onprogress**: 使用調用 `ProgressEvent` 每當一塊新的資料傳輸。*(函數)*
+
+## 方法
+
+ * **upload**: 將檔發送到伺服器。
+
+ * **download**: 從伺服器上下載檔案。
+
+ * **abort**: 中止正在進行轉讓。
+
+## upload
+
+**參數**:
+
+ * **fileURL**: 表示檔在設備上的檔案系統 URL。 為向後相容性,這也可以將設備上的檔的完整路徑。 (請參見 [向後相容性注意到] 下面)
+
+ * **server**: 伺服器以接收該檔,由編碼的 URL`encodeURI()`.
+
+ * **successCallback**: 一個通過一個 `FileUploadResult` 物件的回檔。*(函數)*
+
+ * **errorCallback**: 如果發生錯誤,檢索 `FileUploadResult` 執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)*
+
+ * **options**: 可選參數*(物件)*。有效的金鑰:
+
+ * **fileKey**: 表單元素的名稱。預設值為 `file` 。() DOMString
+ * **fileName**: 要保存在伺服器上的檔時使用的檔案名稱。預設值為 `image.jpg` 。() DOMString
+ * **httpMethod**: HTTP 方法使用-`PUT` 或 `POST`。預設值為 `POST`。() DOMString
+ * **mimeType**: 要上載的資料的 mime 類型。預設設置為 `image/jpeg`。() DOMString
+ * **params**: 一組要在 HTTP 要求中傳遞的可選的鍵值對。(物件)
+ * **chunkedMode**: 是否要分塊的流式處理模式中的資料上載。預設值為 `true`。(布林值)
+ * **headers**: 地圖的標頭名稱/標頭值。 使用陣列來指定多個值。 IOS、 FireOS,和安卓系統,如果已命名的內容類型標頭存在,多部分表單資料不被使用。 (Object)
+ * **httpMethod**: HTTP 方法,例如使用張貼或放。 預設為`開機自檢`。() DOMString
+
+ * **trustAllHosts**: 可選參數,預設值為 `false` 。 如果設置為 `true` ,它可以接受的所有安全證書。 這是有用的因為 android 系統拒絕自簽名的安全證書。 不建議供生產使用。 在 Android 和 iOS 上受支援。 *(布林值)*
+
+### 示例
+
+ // !! 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);
+
+
+### 與上傳的標頭和進度事件 (Android 和 iOS 只) 的示例
+
+ 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
+
+`FileUploadResult` 物件將傳遞給該 `檔案傳輸` 物件的 `upload()` 方法的成功回檔。
+
+### 屬性
+
+ * **bytesSent**: 作為上載的一部分發送到伺服器的位元組數。(長)
+
+ * **responseCode**: 由伺服器返回的 HTTP 回應代碼。(長)
+
+ * **response**: 由伺服器返回的 HTTP 回應。() DOMString
+
+ * **headers**: 由伺服器的 HTTP 回應標頭。(物件)
+
+ * 目前支援的 iOS 只。
+
+### iOS 的怪癖
+
+ * 不支援 `responseCode` 或`bytesSent`.
+
+## download
+
+**參數**:
+
+ * **source**: 要下載的檔,如由編碼的伺服器的 URL`encodeURI()`.
+
+ * **target**: 表示檔在設備上的檔案系統 url。 為向後相容性,這也可以將設備上的檔的完整路徑。 (請參見 [向後相容性注意到] 下面)
+
+ * **successCallback**: 傳遞一個回檔 `FileEntry` 物件。*(函數)*
+
+ * **errorCallback**: 如果檢索 `FileEntry` 時發生錯誤,則執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)*
+
+ * **trustAllHosts**: 可選參數,預設值為 `false` 。 如果設置為 `true` ,它可以接受的所有安全證書。 這是有用的因為 Android 拒絕自行簽署式安全證書。 不建議供生產使用。 在 Android 和 iOS 上受支援。 *(布林值)*
+
+ * **options**: 可選參數,目前只支援標題 (如授權 (基本驗證) 等)。
+
+### 示例
+
+ // !! 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 的怪癖
+
+ * 下載請求由本機實現被緩存。若要避免緩存,傳遞`如果修改自`郵件頭以下載方法。
+
+## abort
+
+中止正在進行轉讓。Onerror 回檔傳遞一個 FileTransferError 物件具有 FileTransferError.ABORT_ERR 錯誤代碼。
+
+### 示例
+
+ // !! 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
+
+當發生錯誤時,`FileTransferError` 物件將傳遞給錯誤回檔。
+
+### 屬性
+
+ * **code**: 下面列出的預定義的錯誤代碼之一。(人數)
+
+ * **source**: 源的 URL。(字串)
+
+ * **target**: 到目標 URL。(字串)
+
+ * **HTTP_status**: HTTP 狀態碼。從 HTTP 連接收到一個回應代碼時,此屬性才可用。(人數)
+
+ * **body**回應正文。此屬性只能是可用的當該 HTTP 連接收到答覆。(字串)
+
+ * **exception**: 要麼 e.getMessage 或 e.toString (字串)
+
+### 常量
+
+ * 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+ * 2 = `FileTransferError.INVALID_URL_ERR`
+ * 3 = `FileTransferError.CONNECTION_ERR`
+ * 4 = `FileTransferError.ABORT_ERR`
+ * 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## 向後相容性注意到
+
+以前版本的這個外掛程式才會接受設備-絕對檔路徑作為源對於上載,或用於下載的目標。這些路徑通常會在表單
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+為向後相容性,這些路徑仍會被接受,和如果您的應用程式已錄得像這些在持久性存儲的路徑,然後他們可以繼續使用。
+
+這些路徑被以前暴露在 `FileEntry` 和由檔外掛程式返回的 `DirectoryEntry` 物件的 `fullPath` 屬性中。 新版本的檔的外掛程式,但是,不再公開這些 JavaScript 的路徑。
+
+如果您要升級到新 (1.0.0 或更高版本) 版本的檔,和你以前一直在使用 `entry.fullPath` 作為參數到 `download()` 或 `upload()`,那麼你將需要更改代碼以使用檔案系統的 Url 來代替。
+
+`FileEntry.toURL()` 和 `DirectoryEntry.toURL()` 返回的表單檔案 URL
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+它可以用在 `download()` 和 `upload()` 兩種方法中的絕對檔路徑位置。
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file-transfer/doc/zh/index.md b/plugins/cordova-plugin-file-transfer/doc/zh/index.md
new file mode 100644
index 0000000..b3af1eb
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/doc/zh/index.md
@@ -0,0 +1,302 @@
+
+
+# cordova-plugin-file-transfer
+
+這個外掛程式允許你上傳和下載檔案。
+
+這個外掛程式定義全域 `FileTransfer`,`FileUploadOptions` 的建構函式。
+
+雖然在全球範圍內,他們不可用直到 `deviceready` 事件之後。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(FileTransfer);
+ }
+
+
+## 安裝
+
+ cordova plugin add cordova-plugin-file-transfer
+
+
+## 支援的平臺
+
+* 亞馬遜火 OS
+* Android 系統
+* 黑莓 10
+* 瀏覽器
+* 火狐瀏覽器的作業系統 * *
+* iOS
+* Windows Phone 7 和 8 *
+* Windows 8
+* Windows
+
+* *不支援 `onprogress` 也 `abort()`*
+
+* * *不支援 `onprogress`*
+
+# FileTransfer
+
+`FileTransfer` 物件提供一種使用 HTTP 多部分 POST 請求的檔上傳,下載檔案以及方式。
+
+## 屬性
+
+* **onprogress**: 使用調用 `ProgressEvent` 每當一塊新的資料傳輸。*(函數)*
+
+## 方法
+
+* **upload**: 將檔發送到伺服器。
+
+* **download**: 從伺服器上下載檔案。
+
+* **abort**: 中止正在進行轉讓。
+
+## upload
+
+**參數**:
+
+* **fileURL**: 表示檔在設備上的檔案系統 URL。 為向後相容性,這也可以將設備上的檔的完整路徑。 (請參見 [向後相容性注意到] 下面)
+
+* **server**: 伺服器以接收該檔,由編碼的 URL`encodeURI()`.
+
+* **successCallback**: 一個通過一個 `FileUploadResult` 物件的回檔。*(函數)*
+
+* **errorCallback**: 如果發生錯誤,檢索 `FileUploadResult` 執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)*
+
+* **options**: 可選參數*(物件)*。有效的金鑰:
+
+ * **fileKey**: 表單元素的名稱。預設值為 `file` 。() DOMString
+ * **fileName**: 要保存在伺服器上的檔時使用的檔案名稱。預設值為 `image.jpg` 。() DOMString
+ * **httpMethod**: HTTP 方法使用-`PUT` 或 `POST`。預設值為 `POST`。() DOMString
+ * **mimeType**: 要上載的資料的 mime 類型。預設設置為 `image/jpeg`。() DOMString
+ * **params**: 一組要在 HTTP 要求中傳遞的可選的鍵值對。(物件)
+ * **chunkedMode**: 是否要分塊的流式處理模式中的資料上載。預設值為 `true`。(布林值)
+ * **headers**: 地圖的標頭名稱/標頭值。使用陣列來指定多個值。(物件)
+
+* **trustAllHosts**: 可選參數,預設值為 `false` 。 如果設置為 `true` ,它接受的所有安全證書。 這是有用的因為 android 系統拒絕自簽名的安全證書。 不建議供生產使用。 支援 Android 和 iOS。 *(布林值)*
+
+### 示例
+
+ // !! 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);
+
+
+### 與上傳的標頭和進度事件 (Android 和 iOS 只) 的示例
+
+ 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
+
+`FileUploadResult` 物件將傳遞給該 `檔案傳輸` 物件的 `upload()` 方法的成功回檔。
+
+### 屬性
+
+* **bytesSent**: 作為上載的一部分發送到伺服器的位元組數。(長)
+
+* **responseCode**: 由伺服器返回的 HTTP 回應代碼。(長)
+
+* **response**: 由伺服器返回的 HTTP 回應。() DOMString
+
+* **headers**: 由伺服器的 HTTP 回應標頭。(物件)
+
+ * 目前支援的 iOS 只。
+
+### iOS 的怪癖
+
+* 不支援 `responseCode` 或`bytesSent`.
+
+## download
+
+**參數**:
+
+* **source**: 要下載的檔,如由編碼的伺服器的 URL`encodeURI()`.
+
+* **target**: 表示檔在設備上的檔案系統 url。 為向後相容性,這也可以將設備上的檔的完整路徑。 (請參見 [向後相容性注意到] 下面)
+
+* **successCallback**: 傳遞一個回檔 `FileEntry` 物件。*(函數)*
+
+* **errorCallback**: 如果檢索 `FileEntry` 時發生錯誤,則執行一個回檔。使用 `FileTransferError` 物件調用。*(函數)*
+
+* **trustAllHosts**: 可選參數,預設值為 `false` 。 如果設置為 `true` ,它可以接受的所有安全證書。 這是有用的因為 Android 拒絕自行簽署式安全證書。 不建議供生產使用。 在 Android 和 iOS 上受支援。 *(布林值)*
+
+* **options**: 可選參數,目前只支援標題 (如授權 (基本驗證) 等)。
+
+### 示例
+
+ // !! 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
+
+中止正在進行轉讓。Onerror 回檔傳遞一個 FileTransferError 物件具有 FileTransferError.ABORT_ERR 錯誤代碼。
+
+### 示例
+
+ // !! 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
+
+當發生錯誤時,`FileTransferError` 物件將傳遞給錯誤回檔。
+
+### 屬性
+
+* **code**: 下面列出的預定義的錯誤代碼之一。(人數)
+
+* **source**: 源的 URL。(字串)
+
+* **target**: 到目標 URL。(字串)
+
+* **HTTP_status**: HTTP 狀態碼。從 HTTP 連接收到一個回應代碼時,此屬性才可用。(人數)
+
+* **body**回應正文。此屬性只能是可用的當該 HTTP 連接收到答覆。(字串)
+
+* **exception**: 要麼 e.getMessage 或 e.toString (字串)
+
+### 常量
+
+* 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
+* 2 = `FileTransferError.INVALID_URL_ERR`
+* 3 = `FileTransferError.CONNECTION_ERR`
+* 4 = `FileTransferError.ABORT_ERR`
+* 5 = `FileTransferError.NOT_MODIFIED_ERR`
+
+## 向後相容性注意到
+
+以前版本的這個外掛程式才會接受設備-絕對檔路徑作為源對於上載,或用於下載的目標。這些路徑通常會在表單
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+為向後相容性,這些路徑仍會被接受,和如果您的應用程式已錄得像這些在持久性存儲的路徑,然後他們可以繼續使用。
+
+這些路徑被以前暴露在 `FileEntry` 和由檔外掛程式返回的 `DirectoryEntry` 物件的 `fullPath` 屬性中。 新版本的檔的外掛程式,但是,不再公開這些 JavaScript 的路徑。
+
+如果您要升級到新 (1.0.0 或更高版本) 版本的檔,和你以前一直在使用 `entry.fullPath` 作為參數到 `download()` 或 `upload()`,那麼你將需要更改代碼以使用檔案系統的 Url 來代替。
+
+`FileEntry.toURL()` 和 `DirectoryEntry.toURL()` 返回的表單檔案 URL
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+它可以用在 `download()` 和 `upload()` 兩種方法中的絕對檔路徑位置。
diff --git a/plugins/cordova-plugin-file-transfer/package.json b/plugins/cordova-plugin-file-transfer/package.json
new file mode 100644
index 0000000..77df533
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "cordova-plugin-file-transfer",
+ "version": "1.4.0",
+ "description": "Cordova File Transfer Plugin",
+ "cordova": {
+ "id": "cordova-plugin-file-transfer",
+ "platforms": [
+ "android",
+ "amazon-fireos",
+ "ubuntu",
+ "blackberry10",
+ "ios",
+ "wp7",
+ "wp8",
+ "windows8",
+ "windows",
+ "firefoxos",
+ "browser"
+ ]
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/apache/cordova-plugin-file-transfer"
+ },
+ "keywords": [
+ "cordova",
+ "file",
+ "transfer",
+ "ecosystem:cordova",
+ "cordova-android",
+ "cordova-amazon-fireos",
+ "cordova-ubuntu",
+ "cordova-blackberry10",
+ "cordova-ios",
+ "cordova-wp7",
+ "cordova-wp8",
+ "cordova-windows8",
+ "cordova-windows",
+ "cordova-firefoxos",
+ "cordova-browser"
+ ],
+ "peerDependencies": {
+ "cordova-plugin-file": ">=3.0.0"
+ },
+ "author": "Apache Software Foundation",
+ "license": "Apache 2.0"
+}
diff --git a/plugins/cordova-plugin-file-transfer/plugin.xml b/plugins/cordova-plugin-file-transfer/plugin.xml
new file mode 100644
index 0000000..1b1c4f1
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/plugin.xml
@@ -0,0 +1,170 @@
+
+
+
+
+ File Transfer
+ Cordova File Transfer Plugin
+ Apache 2.0
+ cordova,file,transfer
+ https://git-wip-us.apache.org/repos/asf/cordova-plugin-file-transfer.git
+ https://issues.apache.org/jira/browse/CB/component/12320650
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java b/plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java
new file mode 100644
index 0000000..1563a39
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/amazon/FileTransfer.java
@@ -0,0 +1,898 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.HttpURLConnection;
+import java.net.URLConnection;
+import java.net.URLDecoder;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.Inflater;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.cordova.Config;
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaResourceApi;
+import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
+import org.apache.cordova.PluginResult;
+import org.apache.cordova.file.FileUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.net.Uri;
+import android.os.Build;
+import android.util.Log;
+import com.amazon.android.webkit.AmazonCookieManager;
+
+public class FileTransfer extends CordovaPlugin {
+
+ private static final String LOG_TAG = "FileTransfer";
+ private static final String LINE_START = "--";
+ private static final String LINE_END = "\r\n";
+ private static final String BOUNDARY = "+++++";
+
+ public static int FILE_NOT_FOUND_ERR = 1;
+ public static int INVALID_URL_ERR = 2;
+ public static int CONNECTION_ERR = 3;
+ public static int ABORTED_ERR = 4;
+
+ private static HashMap activeRequests = new HashMap();
+ private static final int MAX_BUFFER_SIZE = 16 * 1024;
+
+ private static final class RequestContext {
+ String source;
+ String target;
+ File targetFile;
+ CallbackContext callbackContext;
+ InputStream currentInputStream;
+ OutputStream currentOutputStream;
+ boolean aborted;
+ RequestContext(String source, String target, CallbackContext callbackContext) {
+ this.source = source;
+ this.target = target;
+ this.callbackContext = callbackContext;
+ }
+ void sendPluginResult(PluginResult pluginResult) {
+ synchronized (this) {
+ if (!aborted) {
+ callbackContext.sendPluginResult(pluginResult);
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds an interface method to an InputStream to return the number of bytes
+ * read from the raw stream. This is used to track total progress against
+ * the HTTP Content-Length header value from the server.
+ */
+ private static abstract class TrackingInputStream extends FilterInputStream {
+ public TrackingInputStream(final InputStream in) {
+ super(in);
+ }
+ public abstract long getTotalRawBytesRead();
+ }
+
+ private static class ExposedGZIPInputStream extends GZIPInputStream {
+ public ExposedGZIPInputStream(final InputStream in) throws IOException {
+ super(in);
+ }
+ public Inflater getInflater() {
+ return inf;
+ }
+ }
+
+ /**
+ * Provides raw bytes-read tracking for a GZIP input stream. Reports the
+ * total number of compressed bytes read from the input, rather than the
+ * number of uncompressed bytes.
+ */
+ private static class TrackingGZIPInputStream extends TrackingInputStream {
+ private ExposedGZIPInputStream gzin;
+ public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException {
+ super(gzin);
+ this.gzin = gzin;
+ }
+ public long getTotalRawBytesRead() {
+ return gzin.getInflater().getBytesRead();
+ }
+ }
+
+ /**
+ * Provides simple total-bytes-read tracking for an existing InputStream
+ */
+ private static class SimpleTrackingInputStream extends TrackingInputStream {
+ private long bytesRead = 0;
+ public SimpleTrackingInputStream(InputStream stream) {
+ super(stream);
+ }
+
+ private int updateBytesRead(int newBytesRead) {
+ if (newBytesRead != -1) {
+ bytesRead += newBytesRead;
+ }
+ return newBytesRead;
+ }
+
+ @Override
+ public int read() throws IOException {
+ return updateBytesRead(super.read());
+ }
+
+ // Note: FilterInputStream delegates read(byte[] bytes) to the below method,
+ // so we don't override it or else double count (CB-5631).
+ @Override
+ public int read(byte[] bytes, int offset, int count) throws IOException {
+ return updateBytesRead(super.read(bytes, offset, count));
+ }
+
+ public long getTotalRawBytesRead() {
+ return bytesRead;
+ }
+ }
+
+ @Override
+ public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
+ if (action.equals("upload") || action.equals("download")) {
+ String source = args.getString(0);
+ String target = args.getString(1);
+
+ if (action.equals("upload")) {
+ try {
+ source = URLDecoder.decode(source, "UTF-8");
+ upload(source, target, args, callbackContext);
+ } catch (UnsupportedEncodingException e) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "UTF-8 error."));
+ }
+ } else {
+ download(source, target, args, callbackContext);
+ }
+ return true;
+ } else if (action.equals("abort")) {
+ String objectId = args.getString(0);
+ abort(objectId);
+ callbackContext.success();
+ return true;
+ }
+ return false;
+ }
+
+ private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
+ try {
+ for (Iterator> iter = headers.keys(); iter.hasNext(); ) {
+ String headerKey = iter.next().toString();
+ JSONArray headerValues = headers.optJSONArray(headerKey);
+ if (headerValues == null) {
+ headerValues = new JSONArray();
+ headerValues.put(headers.getString(headerKey));
+ }
+ connection.setRequestProperty(headerKey, headerValues.getString(0));
+ for (int i = 1; i < headerValues.length(); ++i) {
+ connection.addRequestProperty(headerKey, headerValues.getString(i));
+ }
+ }
+ } catch (JSONException e1) {
+ // No headers to be manipulated!
+ }
+ }
+
+ /**
+ * Uploads the specified file to the server URL provided using an HTTP multipart request.
+ * @param source Full path of the file on the file system
+ * @param target URL of the server to receive the file
+ * @param args JSON Array of args
+ * @param callbackContext callback id for optional progress reports
+ *
+ * args[2] fileKey Name of file request parameter
+ * args[3] fileName File name to be used on server
+ * args[4] mimeType Describes file content type
+ * args[5] params key:value pairs of user-defined parameters
+ * @return FileUploadResult containing result of upload request
+ */
+ private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ Log.d(LOG_TAG, "upload " + source + " to " + target);
+
+ // Setup the options
+ final String fileKey = getArgument(args, 2, "file");
+ final String fileName = getArgument(args, 3, "image.jpg");
+ final String mimeType = getArgument(args, 4, "image/jpeg");
+ final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
+ final boolean trustEveryone = args.optBoolean(6);
+ // Always use chunked mode unless set to false as per API
+ final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
+ // Look for headers on the params map for backwards compatibility with older Cordova versions.
+ final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);
+ final String objectId = args.getString(9);
+ final String httpMethod = getArgument(args, 10, "POST");
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ Log.d(LOG_TAG, "fileKey: " + fileKey);
+ Log.d(LOG_TAG, "fileName: " + fileName);
+ Log.d(LOG_TAG, "mimeType: " + mimeType);
+ Log.d(LOG_TAG, "params: " + params);
+ Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
+ Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
+ Log.d(LOG_TAG, "headers: " + headers);
+ Log.d(LOG_TAG, "objectId: " + objectId);
+ Log.d(LOG_TAG, "httpMethod: " + httpMethod);
+
+ final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
+ // Accept a path or a URI for the source.
+ Uri tmpSrc = Uri.parse(source);
+ final Uri sourceUri = resourceApi.remapUri(
+ tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));
+
+ int uriType = CordovaResourceApi.getUriType(targetUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
+ Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+ HttpURLConnection conn = null;
+ HostnameVerifier oldHostnameVerifier = null;
+ SSLSocketFactory oldSocketFactory = null;
+ int totalBytes = 0;
+ int fixedLength = -1;
+ try {
+ // Create return object
+ FileUploadResult result = new FileUploadResult();
+ FileProgressResult progress = new FileProgressResult();
+
+ //------------------ CLIENT REQUEST
+ // Open a HTTP connection to the URL based on protocol
+ conn = resourceApi.createHttpConnection(targetUri);
+ if (useHttps && trustEveryone) {
+ // Setup the HTTPS connection class to trust everyone
+ HttpsURLConnection https = (HttpsURLConnection)conn;
+ oldSocketFactory = trustAllHosts(https);
+ // Save the current hostnameVerifier
+ oldHostnameVerifier = https.getHostnameVerifier();
+ // Setup the connection not to verify hostnames
+ https.setHostnameVerifier(DO_NOT_VERIFY);
+ }
+
+ // Allow Inputs
+ conn.setDoInput(true);
+
+ // Allow Outputs
+ conn.setDoOutput(true);
+
+ // Don't use a cached copy.
+ conn.setUseCaches(false);
+
+ // Use a post method.
+ conn.setRequestMethod(httpMethod);
+
+ // if we specified a Content-Type header, don't do multipart form upload
+ boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
+ if (multipartFormUpload) {
+ conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
+ }
+ // Set the cookies on the response
+ String cookie = AmazonCookieManager.getInstance().getCookie(target);
+ if (cookie != null) {
+ conn.setRequestProperty("Cookie", cookie);
+ }
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(conn, headers);
+ }
+
+ /*
+ * Store the non-file portions of the multipart data as a string, so that we can add it
+ * to the contentSize, since it is part of the body of the HTTP request.
+ */
+ StringBuilder beforeData = new StringBuilder();
+ try {
+ for (Iterator> iter = params.keys(); iter.hasNext();) {
+ Object key = iter.next();
+ if(!String.valueOf(key).equals("headers"))
+ {
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"');
+ beforeData.append(LINE_END).append(LINE_END);
+ beforeData.append(params.getString(key.toString()));
+ beforeData.append(LINE_END);
+ }
+ }
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
+ beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
+ beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
+ byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
+ byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");
+
+
+ // Get a input stream of the file on the phone
+ OpenForReadResult readResult = resourceApi.openForRead(sourceUri);
+
+ int stringLength = beforeDataBytes.length + tailParamsBytes.length;
+ if (readResult.length >= 0) {
+ fixedLength = (int)readResult.length;
+ if (multipartFormUpload)
+ fixedLength += stringLength;
+ progress.setLengthComputable(true);
+ progress.setTotal(fixedLength);
+ }
+ Log.d(LOG_TAG, "Content Length: " + fixedLength);
+ // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
+ // http://code.google.com/p/android/issues/detail?id=3164
+ // It also causes OOM if HTTPS is used, even on newer devices.
+ boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
+ useChunkedMode = useChunkedMode || (fixedLength == -1);
+
+ if (useChunkedMode) {
+ conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
+ // Although setChunkedStreamingMode sets this header, setting it explicitly here works
+ // around an OutOfMemoryException when using https.
+ conn.setRequestProperty("Transfer-Encoding", "chunked");
+ } else {
+ conn.setFixedLengthStreamingMode(fixedLength);
+ }
+
+ conn.connect();
+
+ OutputStream sendStream = null;
+ try {
+ sendStream = conn.getOutputStream();
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.currentOutputStream = sendStream;
+ }
+
+ if (multipartFormUpload) {
+ //We don't want to change encoding, we just want this to write for all Unicode.
+ sendStream.write(beforeDataBytes);
+ totalBytes += beforeDataBytes.length;
+ }
+ // create a buffer of maximum size
+ int bytesAvailable = readResult.inputStream.available();
+ int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ byte[] buffer = new byte[bufferSize];
+
+ // read file and write it into form...
+ int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ long prevBytesRead = 0;
+ while (bytesRead > 0) {
+ result.setBytesSent(totalBytes);
+ sendStream.write(buffer, 0, bytesRead);
+ totalBytes += bytesRead;
+ if (totalBytes > prevBytesRead + 102400) {
+ prevBytesRead = totalBytes;
+ Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
+ }
+ bytesAvailable = readResult.inputStream.available();
+ bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ // Send a progress event.
+ progress.setLoaded(totalBytes);
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+
+ if (multipartFormUpload) {
+ // send multipart form data necessary after file data...
+ sendStream.write(tailParamsBytes);
+ totalBytes += tailParamsBytes.length;
+ }
+ sendStream.flush();
+ } finally {
+ safeClose(readResult.inputStream);
+ safeClose(sendStream);
+ }
+ context.currentOutputStream = null;
+ Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);
+
+ //------------------ read the SERVER RESPONSE
+ String responseString;
+ int responseCode = conn.getResponseCode();
+ Log.d(LOG_TAG, "response code: " + responseCode);
+ Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
+ TrackingInputStream inStream = null;
+ try {
+ inStream = getInputStream(conn);
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.currentInputStream = inStream;
+ }
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));
+ byte[] buffer = new byte[1024];
+ int bytesRead = 0;
+ // write bytes to file
+ while ((bytesRead = inStream.read(buffer)) > 0) {
+ out.write(buffer, 0, bytesRead);
+ }
+ responseString = out.toString("UTF-8");
+ } finally {
+ context.currentInputStream = null;
+ safeClose(inStream);
+ }
+
+ Log.d(LOG_TAG, "got response from server");
+ Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));
+
+ // send request and retrieve response
+ result.setResponseCode(responseCode);
+ result.setResponse(responseString);
+
+ context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
+ Log.e(LOG_TAG, error.toString(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
+ Log.e(LOG_TAG, error.toString(), e);
+ Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ } catch (Throwable t) {
+ // Shouldn't happen, but will
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
+ Log.e(LOG_TAG, error.toString(), t);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (conn != null) {
+ // Revert back to the proper verifier and socket factories
+ // Revert back to the proper verifier and socket factories
+ if (trustEveryone && useHttps) {
+ HttpsURLConnection https = (HttpsURLConnection) conn;
+ https.setHostnameVerifier(oldHostnameVerifier);
+ https.setSSLSocketFactory(oldSocketFactory);
+ }
+ }
+ }
+ }
+ });
+ }
+
+ private static void safeClose(Closeable stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
+ String encoding = conn.getContentEncoding();
+ if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
+ return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
+ }
+ return new SimpleTrackingInputStream(conn.getInputStream());
+ }
+
+ // always verify the host - don't check for certificate
+ private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ };
+ // Create a trust manager that does not validate certificate chains
+ private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return new java.security.cert.X509Certificate[] {};
+ }
+
+ public void checkClientTrusted(X509Certificate[] chain,
+ String authType) throws CertificateException {
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain,
+ String authType) throws CertificateException {
+ }
+ } };
+
+ /**
+ * This function will install a trust manager that will blindly trust all SSL
+ * certificates. The reason this code is being added is to enable developers
+ * to do development using self signed SSL certificates on their web server.
+ *
+ * The standard HttpsURLConnection class will throw an exception on self
+ * signed certificates if this code is not run.
+ */
+ private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
+ // Install the all-trusting trust manager
+ SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
+ try {
+ // Install our all trusting manager
+ SSLContext sc = SSLContext.getInstance("TLS");
+ sc.init(null, trustAllCerts, new java.security.SecureRandom());
+ SSLSocketFactory newFactory = sc.getSocketFactory();
+ connection.setSSLSocketFactory(newFactory);
+ } catch (Exception e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+ return oldFactory;
+ }
+
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection) {
+
+ int httpStatus = 0;
+ StringBuilder bodyBuilder = new StringBuilder();
+ String body = null;
+ if (connection != null) {
+ try {
+ if (connection instanceof HttpURLConnection) {
+ httpStatus = ((HttpURLConnection)connection).getResponseCode();
+ InputStream err = ((HttpURLConnection) connection).getErrorStream();
+ if(err != null)
+ {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8"));
+ try {
+ String line = reader.readLine();
+ while(line != null) {
+ bodyBuilder.append(line);
+ line = reader.readLine();
+ if(line != null) {
+ bodyBuilder.append('\n');
+ }
+ }
+ body = bodyBuilder.toString();
+ } finally {
+ reader.close();
+ }
+ }
+ }
+ // IOException can leave connection object in a bad state, so catch all exceptions.
+ } catch (Throwable e) {
+ Log.w(LOG_TAG, "Error getting HTTP status code from connection.", e);
+ }
+ }
+
+ return createFileTransferError(errorCode, source, target, body, httpStatus);
+ }
+
+ /**
+ * Create an error object based on the passed in errorCode
+ * @param errorCode the error
+ * @return JSONObject containing the error
+ */
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus) {
+ JSONObject error = null;
+ try {
+ error = new JSONObject();
+ error.put("code", errorCode);
+ error.put("source", source);
+ error.put("target", target);
+ if(body != null)
+ {
+ error.put("body", body);
+ }
+ if (httpStatus != null) {
+ error.put("http_status", httpStatus);
+ }
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+ return error;
+ }
+
+ /**
+ * Convenience method to read a parameter from the list of JSON args.
+ * @param args the args passed to the Plugin
+ * @param position the position to retrieve the arg from
+ * @param defaultString the default to be used if the arg does not exist
+ * @return String with the retrieved value
+ */
+ private static String getArgument(JSONArray args, int position, String defaultString) {
+ String arg = defaultString;
+ if (args.length() > position) {
+ arg = args.optString(position);
+ if (arg == null || "null".equals(arg)) {
+ arg = defaultString;
+ }
+ }
+ return arg;
+ }
+
+ /**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ *
+ * @param source URL of the server to receive the file
+ * @param target Full path of the file on the file system
+ */
+ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ Log.d(LOG_TAG, "download " + source + " to " + target);
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ final boolean trustEveryone = args.optBoolean(2);
+ final String objectId = args.getString(3);
+ final JSONObject headers = args.optJSONObject(4);
+
+ final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));
+ // Accept a path or a URI for the source.
+ Uri tmpTarget = Uri.parse(target);
+ final Uri targetUri = resourceApi.remapUri(
+ tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));
+
+ int uriType = CordovaResourceApi.getUriType(sourceUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
+ if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
+ Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ // TODO: refactor to also allow resources & content:
+ if (!isLocalTransfer && !Config.isUrlWhiteListed(source)) {
+ Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+ HttpURLConnection connection = null;
+ HostnameVerifier oldHostnameVerifier = null;
+ SSLSocketFactory oldSocketFactory = null;
+ File file = null;
+ PluginResult result = null;
+ TrackingInputStream inputStream = null;
+
+ OutputStream outputStream = null;
+ try {
+ OpenForReadResult readResult = null;
+ outputStream = resourceApi.openOutputStream(targetUri);
+
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+
+ Log.d(LOG_TAG, "Download file:" + sourceUri);
+
+ FileProgressResult progress = new FileProgressResult();
+
+ if (isLocalTransfer) {
+ readResult = resourceApi.openForRead(sourceUri);
+ if (readResult.length != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(readResult.length);
+ }
+ inputStream = new SimpleTrackingInputStream(readResult.inputStream);
+ } else {
+ // connect to server
+ // Open a HTTP connection to the URL based on protocol
+ connection = resourceApi.createHttpConnection(sourceUri);
+ if (useHttps && trustEveryone) {
+ // Setup the HTTPS connection class to trust everyone
+ HttpsURLConnection https = (HttpsURLConnection)connection;
+ oldSocketFactory = trustAllHosts(https);
+ // Save the current hostnameVerifier
+ oldHostnameVerifier = https.getHostnameVerifier();
+ // Setup the connection not to verify hostnames
+ https.setHostnameVerifier(DO_NOT_VERIFY);
+ }
+
+ connection.setRequestMethod("GET");
+
+ // TODO: Make OkHttp use this AmazonCookieManager by default.
+ String cookie = AmazonCookieManager.getInstance().getCookie(sourceUri.toString());
+ if(cookie != null)
+ {
+ connection.setRequestProperty("cookie", cookie);
+ }
+
+ // This must be explicitly set for gzip progress tracking to work.
+ connection.setRequestProperty("Accept-Encoding", "gzip");
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(connection, headers);
+ }
+
+ connection.connect();
+
+ if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
+ // Only trust content-length header if we understand
+ // the encoding -- identity or gzip
+ if (connection.getContentLength() != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(connection.getContentLength());
+ }
+ }
+ inputStream = getInputStream(connection);
+ }
+
+ try {
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.currentInputStream = inputStream;
+ }
+
+ // write bytes to file
+ byte[] buffer = new byte[MAX_BUFFER_SIZE];
+ int bytesRead = 0;
+ while ((bytesRead = inputStream.read(buffer)) > 0) {
+ outputStream.write(buffer, 0, bytesRead);
+ // Send a progress event.
+ progress.setLoaded(inputStream.getTotalRawBytesRead());
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+ } finally {
+ context.currentInputStream = null;
+ safeClose(inputStream);
+ safeClose(outputStream);
+ }
+
+ Log.d(LOG_TAG, "Saved file: " + target);
+
+ // create FileEntry object
+ FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+ if (filePlugin != null) {
+ JSONObject fileEntry = filePlugin.getEntryForFile(file);
+ if (fileEntry != null) {
+ result = new PluginResult(PluginResult.Status.OK, fileEntry);
+ } else {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
+ Log.e(LOG_TAG, "File plugin cannot represent download path");
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ }
+ } else {
+ Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file");
+ result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file");
+ }
+
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
+ } catch (Throwable e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } finally {
+ safeClose(outputStream);
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (connection != null) {
+ // Revert back to the proper verifier and socket factories
+ if (trustEveryone && useHttps) {
+ HttpsURLConnection https = (HttpsURLConnection) connection;
+ https.setHostnameVerifier(oldHostnameVerifier);
+ https.setSSLSocketFactory(oldSocketFactory);
+ }
+ }
+
+ if (result == null) {
+ result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection));
+ }
+ // Remove incomplete download.
+ if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
+ file.delete();
+ }
+ context.sendPluginResult(result);
+ }
+ }
+ });
+ }
+
+ /**
+ * Abort an ongoing upload or download.
+ */
+ private void abort(String objectId) {
+ final RequestContext context;
+ synchronized (activeRequests) {
+ context = activeRequests.remove(objectId);
+ }
+ if (context != null) {
+ File file = context.targetFile;
+ if (file != null) {
+ file.delete();
+ }
+ // Trigger the abort callback immediately to minimize latency between it and abort() being called.
+ JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1);
+ synchronized (context) {
+ context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
+ context.aborted = true;
+ }
+ // Closing the streams can block, so execute on a background thread.
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ synchronized (context) {
+ safeClose(context.currentInputStream);
+ safeClose(context.currentOutputStream);
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java b/plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java
new file mode 100644
index 0000000..76a7b13
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/android/FileProgressResult.java
@@ -0,0 +1,63 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Encapsulates in-progress status of uploading or downloading a file to a remote server.
+ */
+public class FileProgressResult {
+
+ private boolean lengthComputable = false; // declares whether total is known
+ private long loaded = 0; // bytes sent so far
+ private long total = 0; // bytes total, if known
+
+ public boolean getLengthComputable() {
+ return lengthComputable;
+ }
+
+ public void setLengthComputable(boolean computable) {
+ this.lengthComputable = computable;
+ }
+
+ public long getLoaded() {
+ return loaded;
+ }
+
+ public void setLoaded(long bytes) {
+ this.loaded = bytes;
+ }
+
+ public long getTotal() {
+ return total;
+ }
+
+ public void setTotal(long bytes) {
+ this.total = bytes;
+ }
+
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{loaded:" + loaded +
+ ",total:" + total +
+ ",lengthComputable:" + (lengthComputable ? "true" : "false") + "}");
+ }
+}
diff --git a/plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java b/plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java
new file mode 100644
index 0000000..0efbd4e
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/android/FileTransfer.java
@@ -0,0 +1,1025 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
+import java.net.URLConnection;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.Inflater;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.apache.cordova.Config;
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaResourceApi;
+import org.apache.cordova.CordovaResourceApi.OpenForReadResult;
+import org.apache.cordova.PluginManager;
+import org.apache.cordova.PluginResult;
+import org.apache.cordova.Whitelist;
+import org.apache.cordova.file.FileUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.net.Uri;
+import android.os.Build;
+import android.util.Log;
+import android.webkit.CookieManager;
+
+public class FileTransfer extends CordovaPlugin {
+
+ private static final String LOG_TAG = "FileTransfer";
+ private static final String LINE_START = "--";
+ private static final String LINE_END = "\r\n";
+ private static final String BOUNDARY = "+++++";
+
+ public static int FILE_NOT_FOUND_ERR = 1;
+ public static int INVALID_URL_ERR = 2;
+ public static int CONNECTION_ERR = 3;
+ public static int ABORTED_ERR = 4;
+ public static int NOT_MODIFIED_ERR = 5;
+
+ private static HashMap activeRequests = new HashMap();
+ private static final int MAX_BUFFER_SIZE = 16 * 1024;
+
+ private static final class RequestContext {
+ String source;
+ String target;
+ File targetFile;
+ CallbackContext callbackContext;
+ HttpURLConnection connection;
+ boolean aborted;
+ RequestContext(String source, String target, CallbackContext callbackContext) {
+ this.source = source;
+ this.target = target;
+ this.callbackContext = callbackContext;
+ }
+ void sendPluginResult(PluginResult pluginResult) {
+ synchronized (this) {
+ if (!aborted) {
+ callbackContext.sendPluginResult(pluginResult);
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds an interface method to an InputStream to return the number of bytes
+ * read from the raw stream. This is used to track total progress against
+ * the HTTP Content-Length header value from the server.
+ */
+ private static abstract class TrackingInputStream extends FilterInputStream {
+ public TrackingInputStream(final InputStream in) {
+ super(in);
+ }
+ public abstract long getTotalRawBytesRead();
+ }
+
+ private static class ExposedGZIPInputStream extends GZIPInputStream {
+ public ExposedGZIPInputStream(final InputStream in) throws IOException {
+ super(in);
+ }
+ public Inflater getInflater() {
+ return inf;
+ }
+ }
+
+ /**
+ * Provides raw bytes-read tracking for a GZIP input stream. Reports the
+ * total number of compressed bytes read from the input, rather than the
+ * number of uncompressed bytes.
+ */
+ private static class TrackingGZIPInputStream extends TrackingInputStream {
+ private ExposedGZIPInputStream gzin;
+ public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException {
+ super(gzin);
+ this.gzin = gzin;
+ }
+ public long getTotalRawBytesRead() {
+ return gzin.getInflater().getBytesRead();
+ }
+ }
+
+ /**
+ * Provides simple total-bytes-read tracking for an existing InputStream
+ */
+ private static class SimpleTrackingInputStream extends TrackingInputStream {
+ private long bytesRead = 0;
+ public SimpleTrackingInputStream(InputStream stream) {
+ super(stream);
+ }
+
+ private int updateBytesRead(int newBytesRead) {
+ if (newBytesRead != -1) {
+ bytesRead += newBytesRead;
+ }
+ return newBytesRead;
+ }
+
+ @Override
+ public int read() throws IOException {
+ return updateBytesRead(super.read());
+ }
+
+ // Note: FilterInputStream delegates read(byte[] bytes) to the below method,
+ // so we don't override it or else double count (CB-5631).
+ @Override
+ public int read(byte[] bytes, int offset, int count) throws IOException {
+ return updateBytesRead(super.read(bytes, offset, count));
+ }
+
+ public long getTotalRawBytesRead() {
+ return bytesRead;
+ }
+ }
+
+ @Override
+ public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
+ if (action.equals("upload") || action.equals("download")) {
+ String source = args.getString(0);
+ String target = args.getString(1);
+
+ if (action.equals("upload")) {
+ upload(source, target, args, callbackContext);
+ } else {
+ download(source, target, args, callbackContext);
+ }
+ return true;
+ } else if (action.equals("abort")) {
+ String objectId = args.getString(0);
+ abort(objectId);
+ callbackContext.success();
+ return true;
+ }
+ return false;
+ }
+
+ private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
+ try {
+ for (Iterator> iter = headers.keys(); iter.hasNext(); ) {
+ /* RFC 2616 says that non-ASCII characters and control
+ * characters are not allowed in header names or values.
+ * Additionally, spaces are not allowed in header names.
+ * RFC 2046 Quoted-printable encoding may be used to encode
+ * arbitrary characters, but we donon- not do that encoding here.
+ */
+ String headerKey = iter.next().toString();
+ String cleanHeaderKey = headerKey.replaceAll("\\n","")
+ .replaceAll("\\s+","")
+ .replaceAll(":", "")
+ .replaceAll("[^\\x20-\\x7E]+", "");
+
+ JSONArray headerValues = headers.optJSONArray(headerKey);
+ if (headerValues == null) {
+ headerValues = new JSONArray();
+
+ /* RFC 2616 also says that any amount of consecutive linear
+ * whitespace within a header value can be replaced with a
+ * single space character, without affecting the meaning of
+ * that value.
+ */
+
+ String headerValue = headers.getString(headerKey);
+ String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n"," ").replaceAll("[^\\x20-\\x7E]+", " ");
+ headerValues.put(finalValue);
+ }
+
+ //Use the clean header key, not the one that we passed in
+ connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0));
+ for (int i = 1; i < headerValues.length(); ++i) {
+ connection.addRequestProperty(headerKey, headerValues.getString(i));
+ }
+ }
+ } catch (JSONException e1) {
+ // No headers to be manipulated!
+ }
+ }
+
+ private String getCookies(final String target) {
+ boolean gotCookie = false;
+ String cookie = null;
+ Class webViewClass = webView.getClass();
+ try {
+ Method gcmMethod = webViewClass.getMethod("getCookieManager");
+ Class iccmClass = gcmMethod.getReturnType();
+ Method gcMethod = iccmClass.getMethod("getCookie", String.class);
+
+ cookie = (String)gcMethod.invoke(
+ iccmClass.cast(
+ gcmMethod.invoke(webView)
+ ), target);
+
+ gotCookie = true;
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ } catch (ClassCastException e) {
+ }
+
+ if (!gotCookie && CookieManager.getInstance() != null) {
+ cookie = CookieManager.getInstance().getCookie(target);
+ }
+
+ return cookie;
+ }
+
+ /**
+ * Uploads the specified file to the server URL provided using an HTTP multipart request.
+ * @param source Full path of the file on the file system
+ * @param target URL of the server to receive the file
+ * @param args JSON Array of args
+ * @param callbackContext callback id for optional progress reports
+ *
+ * args[2] fileKey Name of file request parameter
+ * args[3] fileName File name to be used on server
+ * args[4] mimeType Describes file content type
+ * args[5] params key:value pairs of user-defined parameters
+ * @return FileUploadResult containing result of upload request
+ */
+ private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ Log.d(LOG_TAG, "upload " + source + " to " + target);
+
+ // Setup the options
+ final String fileKey = getArgument(args, 2, "file");
+ final String fileName = getArgument(args, 3, "image.jpg");
+ final String mimeType = getArgument(args, 4, "image/jpeg");
+ final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5);
+ final boolean trustEveryone = args.optBoolean(6);
+ // Always use chunked mode unless set to false as per API
+ final boolean chunkedMode = args.optBoolean(7) || args.isNull(7);
+ // Look for headers on the params map for backwards compatibility with older Cordova versions.
+ final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);
+ final String objectId = args.getString(9);
+ final String httpMethod = getArgument(args, 10, "POST");
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ Log.d(LOG_TAG, "fileKey: " + fileKey);
+ Log.d(LOG_TAG, "fileName: " + fileName);
+ Log.d(LOG_TAG, "mimeType: " + mimeType);
+ Log.d(LOG_TAG, "params: " + params);
+ Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
+ Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
+ Log.d(LOG_TAG, "headers: " + headers);
+ Log.d(LOG_TAG, "objectId: " + objectId);
+ Log.d(LOG_TAG, "httpMethod: " + httpMethod);
+
+ final Uri targetUri = resourceApi.remapUri(Uri.parse(target));
+ // Accept a path or a URI for the source.
+ Uri tmpSrc = Uri.parse(source);
+ final Uri sourceUri = resourceApi.remapUri(
+ tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source)));
+
+ int uriType = CordovaResourceApi.getUriType(targetUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
+ Log.e(LOG_TAG, "Unsupported URI: " + targetUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+ HttpURLConnection conn = null;
+ HostnameVerifier oldHostnameVerifier = null;
+ SSLSocketFactory oldSocketFactory = null;
+ int totalBytes = 0;
+ int fixedLength = -1;
+ try {
+ // Create return object
+ FileUploadResult result = new FileUploadResult();
+ FileProgressResult progress = new FileProgressResult();
+
+ //------------------ CLIENT REQUEST
+ // Open a HTTP connection to the URL based on protocol
+ conn = resourceApi.createHttpConnection(targetUri);
+ if (useHttps && trustEveryone) {
+ // Setup the HTTPS connection class to trust everyone
+ HttpsURLConnection https = (HttpsURLConnection)conn;
+ oldSocketFactory = trustAllHosts(https);
+ // Save the current hostnameVerifier
+ oldHostnameVerifier = https.getHostnameVerifier();
+ // Setup the connection not to verify hostnames
+ https.setHostnameVerifier(DO_NOT_VERIFY);
+ }
+
+ // Allow Inputs
+ conn.setDoInput(true);
+
+ // Allow Outputs
+ conn.setDoOutput(true);
+
+ // Don't use a cached copy.
+ conn.setUseCaches(false);
+
+ // Use a post method.
+ conn.setRequestMethod(httpMethod);
+
+ // if we specified a Content-Type header, don't do multipart form upload
+ boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type");
+ if (multipartFormUpload) {
+ conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
+ }
+
+ // Set the cookies on the response
+ String cookie = getCookies(target);
+
+ if (cookie != null) {
+ conn.setRequestProperty("Cookie", cookie);
+ }
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(conn, headers);
+ }
+
+ /*
+ * Store the non-file portions of the multipart data as a string, so that we can add it
+ * to the contentSize, since it is part of the body of the HTTP request.
+ */
+ StringBuilder beforeData = new StringBuilder();
+ try {
+ for (Iterator> iter = params.keys(); iter.hasNext();) {
+ Object key = iter.next();
+ if(!String.valueOf(key).equals("headers"))
+ {
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"');
+ beforeData.append(LINE_END).append(LINE_END);
+ beforeData.append(params.getString(key.toString()));
+ beforeData.append(LINE_END);
+ }
+ }
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+
+ beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
+ beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
+ beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
+ beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
+ byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
+ byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");
+
+
+ // Get a input stream of the file on the phone
+ OpenForReadResult readResult = resourceApi.openForRead(sourceUri);
+
+ int stringLength = beforeDataBytes.length + tailParamsBytes.length;
+ if (readResult.length >= 0) {
+ fixedLength = (int)readResult.length;
+ if (multipartFormUpload)
+ fixedLength += stringLength;
+ progress.setLengthComputable(true);
+ progress.setTotal(fixedLength);
+ }
+ Log.d(LOG_TAG, "Content Length: " + fixedLength);
+ // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices.
+ // http://code.google.com/p/android/issues/detail?id=3164
+ // It also causes OOM if HTTPS is used, even on newer devices.
+ boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
+ useChunkedMode = useChunkedMode || (fixedLength == -1);
+
+ if (useChunkedMode) {
+ conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
+ // Although setChunkedStreamingMode sets this header, setting it explicitly here works
+ // around an OutOfMemoryException when using https.
+ conn.setRequestProperty("Transfer-Encoding", "chunked");
+ } else {
+ conn.setFixedLengthStreamingMode(fixedLength);
+ }
+
+ conn.connect();
+
+ OutputStream sendStream = null;
+ try {
+ sendStream = conn.getOutputStream();
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = conn;
+ }
+
+ if (multipartFormUpload) {
+ //We don't want to change encoding, we just want this to write for all Unicode.
+ sendStream.write(beforeDataBytes);
+ totalBytes += beforeDataBytes.length;
+ }
+
+ // create a buffer of maximum size
+ int bytesAvailable = readResult.inputStream.available();
+ int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ byte[] buffer = new byte[bufferSize];
+
+ // read file and write it into form...
+ int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ long prevBytesRead = 0;
+ while (bytesRead > 0) {
+ result.setBytesSent(totalBytes);
+ sendStream.write(buffer, 0, bytesRead);
+ totalBytes += bytesRead;
+ if (totalBytes > prevBytesRead + 102400) {
+ prevBytesRead = totalBytes;
+ Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
+ }
+ bytesAvailable = readResult.inputStream.available();
+ bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
+ bytesRead = readResult.inputStream.read(buffer, 0, bufferSize);
+
+ // Send a progress event.
+ progress.setLoaded(totalBytes);
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+
+ if (multipartFormUpload) {
+ // send multipart form data necessary after file data...
+ sendStream.write(tailParamsBytes);
+ totalBytes += tailParamsBytes.length;
+ }
+ sendStream.flush();
+ } finally {
+ safeClose(readResult.inputStream);
+ safeClose(sendStream);
+ }
+ synchronized (context) {
+ context.connection = null;
+ }
+ Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);
+
+ //------------------ read the SERVER RESPONSE
+ String responseString;
+ int responseCode = conn.getResponseCode();
+ Log.d(LOG_TAG, "response code: " + responseCode);
+ Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
+ TrackingInputStream inStream = null;
+ try {
+ inStream = getInputStream(conn);
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = conn;
+ }
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));
+ byte[] buffer = new byte[1024];
+ int bytesRead = 0;
+ // write bytes to file
+ while ((bytesRead = inStream.read(buffer)) > 0) {
+ out.write(buffer, 0, bytesRead);
+ }
+ responseString = out.toString("UTF-8");
+ } finally {
+ synchronized (context) {
+ context.connection = null;
+ }
+ safeClose(inStream);
+ }
+
+ Log.d(LOG_TAG, "got response from server");
+ Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length())));
+
+ // send request and retrieve response
+ result.setResponseCode(responseCode);
+ result.setResponse(responseString);
+
+ context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject()));
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ } catch (Throwable t) {
+ // Shouldn't happen, but will
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t);
+ Log.e(LOG_TAG, error.toString(), t);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (conn != null) {
+ // Revert back to the proper verifier and socket factories
+ // Revert back to the proper verifier and socket factories
+ if (trustEveryone && useHttps) {
+ HttpsURLConnection https = (HttpsURLConnection) conn;
+ https.setHostnameVerifier(oldHostnameVerifier);
+ https.setSSLSocketFactory(oldSocketFactory);
+ }
+ }
+ }
+ }
+ });
+ }
+
+ private static void safeClose(Closeable stream) {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
+ String encoding = conn.getContentEncoding();
+ if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
+ return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
+ }
+ return new SimpleTrackingInputStream(conn.getInputStream());
+ }
+
+ // always verify the host - don't check for certificate
+ private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ };
+ // Create a trust manager that does not validate certificate chains
+ private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return new java.security.cert.X509Certificate[] {};
+ }
+
+ public void checkClientTrusted(X509Certificate[] chain,
+ String authType) throws CertificateException {
+ }
+
+ public void checkServerTrusted(X509Certificate[] chain,
+ String authType) throws CertificateException {
+ }
+ } };
+
+ /**
+ * This function will install a trust manager that will blindly trust all SSL
+ * certificates. The reason this code is being added is to enable developers
+ * to do development using self signed SSL certificates on their web server.
+ *
+ * The standard HttpsURLConnection class will throw an exception on self
+ * signed certificates if this code is not run.
+ */
+ private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
+ // Install the all-trusting trust manager
+ SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
+ try {
+ // Install our all trusting manager
+ SSLContext sc = SSLContext.getInstance("TLS");
+ sc.init(null, trustAllCerts, new java.security.SecureRandom());
+ SSLSocketFactory newFactory = sc.getSocketFactory();
+ connection.setSSLSocketFactory(newFactory);
+ } catch (Exception e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+ return oldFactory;
+ }
+
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection, Throwable throwable) {
+
+ int httpStatus = 0;
+ StringBuilder bodyBuilder = new StringBuilder();
+ String body = null;
+ if (connection != null) {
+ try {
+ if (connection instanceof HttpURLConnection) {
+ httpStatus = ((HttpURLConnection)connection).getResponseCode();
+ InputStream err = ((HttpURLConnection) connection).getErrorStream();
+ if(err != null)
+ {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8"));
+ try {
+ String line = reader.readLine();
+ while(line != null) {
+ bodyBuilder.append(line);
+ line = reader.readLine();
+ if(line != null) {
+ bodyBuilder.append('\n');
+ }
+ }
+ body = bodyBuilder.toString();
+ } finally {
+ reader.close();
+ }
+ }
+ }
+ // IOException can leave connection object in a bad state, so catch all exceptions.
+ } catch (Throwable e) {
+ Log.w(LOG_TAG, "Error getting HTTP status code from connection.", e);
+ }
+ }
+
+ return createFileTransferError(errorCode, source, target, body, httpStatus, throwable);
+ }
+
+ /**
+ * Create an error object based on the passed in errorCode
+ * @param errorCode the error
+ * @return JSONObject containing the error
+ */
+ private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) {
+ JSONObject error = null;
+ try {
+ error = new JSONObject();
+ error.put("code", errorCode);
+ error.put("source", source);
+ error.put("target", target);
+ if(body != null)
+ {
+ error.put("body", body);
+ }
+ if (httpStatus != null) {
+ error.put("http_status", httpStatus);
+ }
+ if (throwable != null) {
+ String msg = throwable.getMessage();
+ if (msg == null || "".equals(msg)) {
+ msg = throwable.toString();
+ }
+ error.put("exception", msg);
+ }
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ }
+ return error;
+ }
+
+ /**
+ * Convenience method to read a parameter from the list of JSON args.
+ * @param args the args passed to the Plugin
+ * @param position the position to retrieve the arg from
+ * @param defaultString the default to be used if the arg does not exist
+ * @return String with the retrieved value
+ */
+ private static String getArgument(JSONArray args, int position, String defaultString) {
+ String arg = defaultString;
+ if (args.length() > position) {
+ arg = args.optString(position);
+ if (arg == null || "null".equals(arg)) {
+ arg = defaultString;
+ }
+ }
+ return arg;
+ }
+
+ /**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ *
+ * @param source URL of the server to receive the file
+ * @param target Full path of the file on the file system
+ */
+ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException {
+ Log.d(LOG_TAG, "download " + source + " to " + target);
+
+ final CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ final boolean trustEveryone = args.optBoolean(2);
+ final String objectId = args.getString(3);
+ final JSONObject headers = args.optJSONObject(4);
+
+ final Uri sourceUri = resourceApi.remapUri(Uri.parse(source));
+ // Accept a path or a URI for the source.
+ Uri tmpTarget = Uri.parse(target);
+ final Uri targetUri = resourceApi.remapUri(
+ tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target)));
+
+ int uriType = CordovaResourceApi.getUriType(sourceUri);
+ final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS;
+ final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP;
+ if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) {
+ JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null);
+ Log.e(LOG_TAG, "Unsupported URI: " + sourceUri);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+ /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
+ * Previously the CordovaWebView class had a method, getWhitelist, which would
+ * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x,
+ * the correct call now is to shouldAllowRequest from the plugin manager.
+ */
+ Boolean shouldAllowRequest = null;
+ if (isLocalTransfer) {
+ shouldAllowRequest = true;
+ }
+ if (shouldAllowRequest == null) {
+ try {
+ Method gwl = webView.getClass().getMethod("getWhitelist");
+ Whitelist whitelist = (Whitelist)gwl.invoke(webView);
+ shouldAllowRequest = whitelist.isUrlWhiteListed(source);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+ if (shouldAllowRequest == null) {
+ try {
+ Method gpm = webView.getClass().getMethod("getPluginManager");
+ PluginManager pm = (PluginManager)gpm.invoke(webView);
+ Method san = pm.getClass().getMethod("shouldAllowRequest", String.class);
+ shouldAllowRequest = (Boolean)san.invoke(pm, source);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+
+ if (!Boolean.TRUE.equals(shouldAllowRequest)) {
+ Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
+ return;
+ }
+
+
+ final RequestContext context = new RequestContext(source, target, callbackContext);
+ synchronized (activeRequests) {
+ activeRequests.put(objectId, context);
+ }
+
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ if (context.aborted) {
+ return;
+ }
+ HttpURLConnection connection = null;
+ HostnameVerifier oldHostnameVerifier = null;
+ SSLSocketFactory oldSocketFactory = null;
+ File file = null;
+ PluginResult result = null;
+ TrackingInputStream inputStream = null;
+ boolean cached = false;
+
+ OutputStream outputStream = null;
+ try {
+ OpenForReadResult readResult = null;
+
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+
+ Log.d(LOG_TAG, "Download file:" + sourceUri);
+
+ FileProgressResult progress = new FileProgressResult();
+
+ if (isLocalTransfer) {
+ readResult = resourceApi.openForRead(sourceUri);
+ if (readResult.length != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(readResult.length);
+ }
+ inputStream = new SimpleTrackingInputStream(readResult.inputStream);
+ } else {
+ // connect to server
+ // Open a HTTP connection to the URL based on protocol
+ connection = resourceApi.createHttpConnection(sourceUri);
+ if (useHttps && trustEveryone) {
+ // Setup the HTTPS connection class to trust everyone
+ HttpsURLConnection https = (HttpsURLConnection)connection;
+ oldSocketFactory = trustAllHosts(https);
+ // Save the current hostnameVerifier
+ oldHostnameVerifier = https.getHostnameVerifier();
+ // Setup the connection not to verify hostnames
+ https.setHostnameVerifier(DO_NOT_VERIFY);
+ }
+
+ connection.setRequestMethod("GET");
+
+ // TODO: Make OkHttp use this CookieManager by default.
+ String cookie = getCookies(sourceUri.toString());
+
+ if(cookie != null)
+ {
+ connection.setRequestProperty("cookie", cookie);
+ }
+
+ // This must be explicitly set for gzip progress tracking to work.
+ connection.setRequestProperty("Accept-Encoding", "gzip");
+
+ // Handle the other headers
+ if (headers != null) {
+ addHeadersToRequest(connection, headers);
+ }
+
+ connection.connect();
+ if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
+ cached = true;
+ connection.disconnect();
+ Log.d(LOG_TAG, "Resource not modified: " + source);
+ JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null);
+ result = new PluginResult(PluginResult.Status.ERROR, error);
+ } else {
+ if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
+ // Only trust content-length header if we understand
+ // the encoding -- identity or gzip
+ if (connection.getContentLength() != -1) {
+ progress.setLengthComputable(true);
+ progress.setTotal(connection.getContentLength());
+ }
+ }
+ inputStream = getInputStream(connection);
+ }
+ }
+
+ if (!cached) {
+ try {
+ synchronized (context) {
+ if (context.aborted) {
+ return;
+ }
+ context.connection = connection;
+ }
+
+ // write bytes to file
+ byte[] buffer = new byte[MAX_BUFFER_SIZE];
+ int bytesRead = 0;
+ outputStream = resourceApi.openOutputStream(targetUri);
+ while ((bytesRead = inputStream.read(buffer)) > 0) {
+ outputStream.write(buffer, 0, bytesRead);
+ // Send a progress event.
+ progress.setLoaded(inputStream.getTotalRawBytesRead());
+ PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
+ progressResult.setKeepCallback(true);
+ context.sendPluginResult(progressResult);
+ }
+ } finally {
+ synchronized (context) {
+ context.connection = null;
+ }
+ safeClose(inputStream);
+ safeClose(outputStream);
+ }
+
+ Log.d(LOG_TAG, "Saved file: " + target);
+
+
+ // create FileEntry object
+ Class webViewClass = webView.getClass();
+ PluginManager pm = null;
+ try {
+ Method gpm = webViewClass.getMethod("getPluginManager");
+ pm = (PluginManager) gpm.invoke(webView);
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ if (pm == null) {
+ try {
+ Field pmf = webViewClass.getField("pluginManager");
+ pm = (PluginManager)pmf.get(webView);
+ } catch (NoSuchFieldException e) {
+ } catch (IllegalAccessException e) {
+ }
+ }
+ file = resourceApi.mapUriToFile(targetUri);
+ context.targetFile = file;
+ FileUtils filePlugin = (FileUtils) pm.getPlugin("File");
+ if (filePlugin != null) {
+ JSONObject fileEntry = filePlugin.getEntryForFile(file);
+ if (fileEntry != null) {
+ result = new PluginResult(PluginResult.Status.OK, fileEntry);
+ } else {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null);
+ Log.e(LOG_TAG, "File plugin cannot represent download path");
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ }
+ } else {
+ Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file");
+ result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file");
+ }
+ }
+
+ } catch (FileNotFoundException e) {
+ JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (IOException e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } catch (JSONException e) {
+ Log.e(LOG_TAG, e.getMessage(), e);
+ result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
+ } catch (Throwable e) {
+ JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e);
+ Log.e(LOG_TAG, error.toString(), e);
+ result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
+ } finally {
+ synchronized (activeRequests) {
+ activeRequests.remove(objectId);
+ }
+
+ if (connection != null) {
+ // Revert back to the proper verifier and socket factories
+ if (trustEveryone && useHttps) {
+ HttpsURLConnection https = (HttpsURLConnection) connection;
+ https.setHostnameVerifier(oldHostnameVerifier);
+ https.setSSLSocketFactory(oldSocketFactory);
+ }
+ }
+
+ if (result == null) {
+ result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null));
+ }
+ // Remove incomplete download.
+ if (!cached && result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
+ file.delete();
+ }
+ context.sendPluginResult(result);
+ }
+ }
+ });
+ }
+
+ /**
+ * Abort an ongoing upload or download.
+ */
+ private void abort(String objectId) {
+ final RequestContext context;
+ synchronized (activeRequests) {
+ context = activeRequests.remove(objectId);
+ }
+ if (context != null) {
+ // Closing the streams can block, so execute on a background thread.
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ synchronized (context) {
+ File file = context.targetFile;
+ if (file != null) {
+ file.delete();
+ }
+ // Trigger the abort callback immediately to minimize latency between it and abort() being called.
+ JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null);
+ context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
+ context.aborted = true;
+ if (context.connection != null) {
+ try {
+ context.connection.disconnect();
+ } catch (Exception e) {
+ Log.e(LOG_TAG, "CB-8431 Catch workaround for fatal exception", e);
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java b/plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java
new file mode 100644
index 0000000..c24ea78
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/android/FileUploadResult.java
@@ -0,0 +1,73 @@
+/*
+ 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.
+*/
+package org.apache.cordova.filetransfer;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Encapsulates the result and/or status of uploading a file to a remote server.
+ */
+public class FileUploadResult {
+
+ private long bytesSent = 0; // bytes sent
+ private int responseCode = -1; // HTTP response code
+ private String response = null; // HTTP response
+ private String objectId = null; // FileTransfer object id
+
+ public long getBytesSent() {
+ return bytesSent;
+ }
+
+ public void setBytesSent(long bytes) {
+ this.bytesSent = bytes;
+ }
+
+ public int getResponseCode() {
+ return responseCode;
+ }
+
+ public void setResponseCode(int responseCode) {
+ this.responseCode = responseCode;
+ }
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public String getObjectId() {
+ return objectId;
+ }
+
+ public void setObjectId(String objectId) {
+ this.objectId = objectId;
+ }
+
+ public JSONObject toJSONObject() throws JSONException {
+ return new JSONObject(
+ "{bytesSent:" + bytesSent +
+ ",responseCode:" + responseCode +
+ ",response:" + JSONObject.quote(response) +
+ ",objectId:" + JSONObject.quote(objectId) + "}");
+ }
+}
diff --git a/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h b/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h
new file mode 100644
index 0000000..bb5fa13
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.h
@@ -0,0 +1,88 @@
+/*
+ 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.
+ */
+
+#import
+#import
+#import "CDVFile.h"
+
+enum CDVFileTransferError {
+ FILE_NOT_FOUND_ERR = 1,
+ INVALID_URL_ERR = 2,
+ CONNECTION_ERR = 3,
+ CONNECTION_ABORTED = 4,
+ NOT_MODIFIED = 5
+};
+typedef int CDVFileTransferError;
+
+enum CDVFileTransferDirection {
+ CDV_TRANSFER_UPLOAD = 1,
+ CDV_TRANSFER_DOWNLOAD = 2,
+};
+typedef int CDVFileTransferDirection;
+
+// Magic value within the options dict used to set a cookie.
+extern NSString* const kOptionsKeyCookie;
+
+@interface CDVFileTransfer : CDVPlugin {}
+
+- (void)upload:(CDVInvokedUrlCommand*)command;
+- (void)download:(CDVInvokedUrlCommand*)command;
+- (NSString*)escapePathComponentForUrlString:(NSString*)urlString;
+
+// Visible for testing.
+- (NSURLRequest*)requestForUploadCommand:(CDVInvokedUrlCommand*)command fileData:(NSData*)fileData;
+- (NSMutableDictionary*)createFileTransferError:(int)code AndSource:(NSString*)source AndTarget:(NSString*)target;
+
+- (NSMutableDictionary*)createFileTransferError:(int)code
+ AndSource:(NSString*)source
+ AndTarget:(NSString*)target
+ AndHttpStatus:(int)httpStatus
+ AndBody:(NSString*)body;
+@property (nonatomic, strong) NSOperationQueue* queue;
+@property (readonly) NSMutableDictionary* activeTransfers;
+@end
+
+@class CDVFileTransferEntityLengthRequest;
+
+@interface CDVFileTransferDelegate : NSObject {}
+
+- (void)updateBytesExpected:(long long)newBytesExpected;
+- (void)cancelTransfer:(NSURLConnection*)connection;
+
+@property (strong) NSMutableData* responseData; // atomic
+@property (nonatomic, strong) NSDictionary* responseHeaders;
+@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskID;
+@property (nonatomic, strong) CDVFileTransfer* command;
+@property (nonatomic, assign) CDVFileTransferDirection direction;
+@property (nonatomic, strong) NSURLConnection* connection;
+@property (nonatomic, copy) NSString* callbackId;
+@property (nonatomic, copy) NSString* objectId;
+@property (nonatomic, copy) NSString* source;
+@property (nonatomic, copy) NSString* target;
+@property (nonatomic, copy) NSURL* targetURL;
+@property (nonatomic, copy) NSString* mimeType;
+@property (assign) int responseCode; // atomic
+@property (nonatomic, assign) long long bytesTransfered;
+@property (nonatomic, assign) long long bytesExpected;
+@property (nonatomic, assign) BOOL trustAllHosts;
+@property (strong) NSFileHandle* targetFileHandle;
+@property (nonatomic, strong) CDVFileTransferEntityLengthRequest* entityLengthRequest;
+@property (nonatomic, strong) CDVFile *filePlugin;
+
+@end
diff --git a/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m b/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m
new file mode 100644
index 0000000..dca440a
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m
@@ -0,0 +1,808 @@
+/*
+ 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.
+ */
+
+#import
+#import "CDVFileTransfer.h"
+#import "CDVLocalFilesystem.h"
+
+#import
+#import
+#import
+#import
+
+#ifndef DLog
+#ifdef DEBUG
+ #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
+#else
+ #define DLog(...)
+#endif
+#endif
+
+@interface CDVFileTransfer ()
+// Sets the requests headers for the request.
+- (void)applyRequestHeaders:(NSDictionary*)headers toRequest:(NSMutableURLRequest*)req;
+// Creates a delegate to handle an upload.
+- (CDVFileTransferDelegate*)delegateForUploadCommand:(CDVInvokedUrlCommand*)command;
+// Creates an NSData* for the file for the given upload arguments.
+- (void)fileDataForUploadCommand:(CDVInvokedUrlCommand*)command;
+@end
+
+// Buffer size to use for streaming uploads.
+static const NSUInteger kStreamBufferSize = 32768;
+// Magic value within the options dict used to set a cookie.
+NSString* const kOptionsKeyCookie = @"__cookie";
+// Form boundary for multi-part requests.
+NSString* const kFormBoundary = @"+++++org.apache.cordova.formBoundary";
+
+// Writes the given data to the stream in a blocking way.
+// If successful, returns bytesToWrite.
+// If the stream was closed on the other end, returns 0.
+// If there was an error, returns -1.
+static CFIndex WriteDataToStream(NSData* data, CFWriteStreamRef stream)
+{
+ UInt8* bytes = (UInt8*)[data bytes];
+ long long bytesToWrite = [data length];
+ long long totalBytesWritten = 0;
+
+ while (totalBytesWritten < bytesToWrite) {
+ CFIndex result = CFWriteStreamWrite(stream,
+ bytes + totalBytesWritten,
+ bytesToWrite - totalBytesWritten);
+ if (result < 0) {
+ CFStreamError error = CFWriteStreamGetError(stream);
+ NSLog(@"WriteStreamError domain: %ld error: %ld", error.domain, (long)error.error);
+ return result;
+ } else if (result == 0) {
+ return result;
+ }
+ totalBytesWritten += result;
+ }
+
+ return totalBytesWritten;
+}
+
+@implementation CDVFileTransfer
+@synthesize activeTransfers;
+
+- (void)pluginInitialize {
+ activeTransfers = [[NSMutableDictionary alloc] init];
+}
+
+- (NSString*)escapePathComponentForUrlString:(NSString*)urlString
+{
+ NSRange schemeAndHostRange = [urlString rangeOfString:@"://.*?/" options:NSRegularExpressionSearch];
+
+ if (schemeAndHostRange.length == 0) {
+ return urlString;
+ }
+
+ NSInteger schemeAndHostEndIndex = NSMaxRange(schemeAndHostRange);
+ NSString* schemeAndHost = [urlString substringToIndex:schemeAndHostEndIndex];
+ NSString* pathComponent = [urlString substringFromIndex:schemeAndHostEndIndex];
+ pathComponent = [pathComponent stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
+
+ return [schemeAndHost stringByAppendingString:pathComponent];
+}
+
+- (void)applyRequestHeaders:(NSDictionary*)headers toRequest:(NSMutableURLRequest*)req
+{
+ [req setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
+
+ NSString* userAgent = [self.commandDelegate userAgent];
+ if (userAgent) {
+ [req setValue:userAgent forHTTPHeaderField:@"User-Agent"];
+ }
+
+ for (NSString* headerName in headers) {
+ id value = [headers objectForKey:headerName];
+ if (!value || (value == [NSNull null])) {
+ value = @"null";
+ }
+
+ // First, remove an existing header if one exists.
+ [req setValue:nil forHTTPHeaderField:headerName];
+
+ if (![value isKindOfClass:[NSArray class]]) {
+ value = [NSArray arrayWithObject:value];
+ }
+
+ // Then, append all header values.
+ for (id __strong subValue in value) {
+ // Convert from an NSNumber -> NSString.
+ if ([subValue respondsToSelector:@selector(stringValue)]) {
+ subValue = [subValue stringValue];
+ }
+ if ([subValue isKindOfClass:[NSString class]]) {
+ [req addValue:subValue forHTTPHeaderField:headerName];
+ }
+ }
+ }
+}
+
+- (NSURLRequest*)requestForUploadCommand:(CDVInvokedUrlCommand*)command fileData:(NSData*)fileData
+{
+ // arguments order from js: [filePath, server, fileKey, fileName, mimeType, params, debug, chunkedMode]
+ // however, params is a JavaScript object and during marshalling is put into the options dict,
+ // thus debug and chunkedMode are the 6th and 7th arguments
+ NSString* target = [command argumentAtIndex:0];
+ NSString* server = [command argumentAtIndex:1];
+ NSString* fileKey = [command argumentAtIndex:2 withDefault:@"file"];
+ NSString* fileName = [command argumentAtIndex:3 withDefault:@"image.jpg"];
+ NSString* mimeType = [command argumentAtIndex:4 withDefault:@"image/jpeg"];
+ NSDictionary* options = [command argumentAtIndex:5 withDefault:nil];
+ // BOOL trustAllHosts = [[command argumentAtIndex:6 withDefault:[NSNumber numberWithBool:YES]] boolValue]; // allow self-signed certs
+ BOOL chunkedMode = [[command argumentAtIndex:7 withDefault:[NSNumber numberWithBool:YES]] boolValue];
+ NSDictionary* headers = [command argumentAtIndex:8 withDefault:nil];
+ // Allow alternative http method, default to POST. JS side checks
+ // for allowed methods, currently PUT or POST (forces POST for
+ // unrecognised values)
+ NSString* httpMethod = [command argumentAtIndex:10 withDefault:@"POST"];
+ CDVPluginResult* result = nil;
+ CDVFileTransferError errorCode = 0;
+
+ // NSURL does not accepts URLs with spaces in the path. We escape the path in order
+ // to be more lenient.
+ NSURL* url = [NSURL URLWithString:server];
+
+ if (!url) {
+ errorCode = INVALID_URL_ERR;
+ NSLog(@"File Transfer Error: Invalid server URL %@", server);
+ } else if (!fileData) {
+ errorCode = FILE_NOT_FOUND_ERR;
+ }
+
+ if (errorCode > 0) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:errorCode AndSource:target AndTarget:server]];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return nil;
+ }
+
+ NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url];
+
+ [req setHTTPMethod:httpMethod];
+
+ // Magic value to set a cookie
+ if ([options objectForKey:kOptionsKeyCookie]) {
+ [req setValue:[options objectForKey:kOptionsKeyCookie] forHTTPHeaderField:@"Cookie"];
+ [req setHTTPShouldHandleCookies:NO];
+ }
+
+ // if we specified a Content-Type header, don't do multipart form upload
+ BOOL multipartFormUpload = [headers objectForKey:@"Content-Type"] == nil;
+ if (multipartFormUpload) {
+ NSString* contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", kFormBoundary];
+ [req setValue:contentType forHTTPHeaderField:@"Content-Type"];
+ }
+ [self applyRequestHeaders:headers toRequest:req];
+
+ NSData* formBoundaryData = [[NSString stringWithFormat:@"--%@\r\n", kFormBoundary] dataUsingEncoding:NSUTF8StringEncoding];
+ NSMutableData* postBodyBeforeFile = [NSMutableData data];
+
+ for (NSString* key in options) {
+ id val = [options objectForKey:key];
+ if (!val || (val == [NSNull null]) || [key isEqualToString:kOptionsKeyCookie]) {
+ continue;
+ }
+ // if it responds to stringValue selector (eg NSNumber) get the NSString
+ if ([val respondsToSelector:@selector(stringValue)]) {
+ val = [val stringValue];
+ }
+ // finally, check whether it is a NSString (for dataUsingEncoding selector below)
+ if (![val isKindOfClass:[NSString class]]) {
+ continue;
+ }
+
+ [postBodyBeforeFile appendData:formBoundaryData];
+ [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
+ [postBodyBeforeFile appendData:[val dataUsingEncoding:NSUTF8StringEncoding]];
+ [postBodyBeforeFile appendData:[@"\r\n" dataUsingEncoding : NSUTF8StringEncoding]];
+ }
+
+ [postBodyBeforeFile appendData:formBoundaryData];
+ [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileKey, fileName] dataUsingEncoding:NSUTF8StringEncoding]];
+ if (mimeType != nil) {
+ [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType] dataUsingEncoding:NSUTF8StringEncoding]];
+ }
+ [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Length: %ld\r\n\r\n", (long)[fileData length]] dataUsingEncoding:NSUTF8StringEncoding]];
+
+ DLog(@"fileData length: %d", [fileData length]);
+ NSData* postBodyAfterFile = [[NSString stringWithFormat:@"\r\n--%@--\r\n", kFormBoundary] dataUsingEncoding:NSUTF8StringEncoding];
+
+ long long totalPayloadLength = [fileData length];
+ if (multipartFormUpload) {
+ totalPayloadLength += [postBodyBeforeFile length] + [postBodyAfterFile length];
+ }
+
+ [req setValue:[[NSNumber numberWithLongLong:totalPayloadLength] stringValue] forHTTPHeaderField:@"Content-Length"];
+
+ if (chunkedMode) {
+ CFReadStreamRef readStream = NULL;
+ CFWriteStreamRef writeStream = NULL;
+ CFStreamCreateBoundPair(NULL, &readStream, &writeStream, kStreamBufferSize);
+ [req setHTTPBodyStream:CFBridgingRelease(readStream)];
+
+ [self.commandDelegate runInBackground:^{
+ if (CFWriteStreamOpen(writeStream)) {
+ if (multipartFormUpload) {
+ NSData* chunks[] = { postBodyBeforeFile, fileData, postBodyAfterFile };
+ int numChunks = sizeof(chunks) / sizeof(chunks[0]);
+
+ for (int i = 0; i < numChunks; ++i) {
+ CFIndex result = WriteDataToStream(chunks[i], writeStream);
+ if (result <= 0) {
+ break;
+ }
+ }
+ } else {
+ WriteDataToStream(fileData, writeStream);
+ }
+ } else {
+ NSLog(@"FileTransfer: Failed to open writeStream");
+ }
+ CFWriteStreamClose(writeStream);
+ CFRelease(writeStream);
+ }];
+ } else {
+ if (multipartFormUpload) {
+ [postBodyBeforeFile appendData:fileData];
+ [postBodyBeforeFile appendData:postBodyAfterFile];
+ [req setHTTPBody:postBodyBeforeFile];
+ } else {
+ [req setHTTPBody:fileData];
+ }
+ }
+ return req;
+}
+
+- (CDVFileTransferDelegate*)delegateForUploadCommand:(CDVInvokedUrlCommand*)command
+{
+ NSString* source = [command argumentAtIndex:0];
+ NSString* server = [command argumentAtIndex:1];
+ BOOL trustAllHosts = [[command argumentAtIndex:6 withDefault:[NSNumber numberWithBool:NO]] boolValue]; // allow self-signed certs
+ NSString* objectId = [command argumentAtIndex:9];
+
+ CDVFileTransferDelegate* delegate = [[CDVFileTransferDelegate alloc] init];
+
+ delegate.command = self;
+ delegate.callbackId = command.callbackId;
+ delegate.direction = CDV_TRANSFER_UPLOAD;
+ delegate.objectId = objectId;
+ delegate.source = source;
+ delegate.target = server;
+ delegate.trustAllHosts = trustAllHosts;
+ delegate.filePlugin = [self.commandDelegate getCommandInstance:@"File"];
+
+ return delegate;
+}
+
+- (void)fileDataForUploadCommand:(CDVInvokedUrlCommand*)command
+{
+ NSString* source = (NSString*)[command argumentAtIndex:0];
+ NSString* server = [command argumentAtIndex:1];
+ NSError* __autoreleasing err = nil;
+
+ CDVFilesystemURL *sourceURL = [CDVFilesystemURL fileSystemURLWithString:source];
+ NSObject *fs;
+ if (sourceURL) {
+ // Try to get a CDVFileSystem which will handle this file.
+ // This requires talking to the current CDVFile plugin.
+ fs = [[self.commandDelegate getCommandInstance:@"File"] filesystemForURL:sourceURL];
+ }
+ if (fs) {
+ [fs readFileAtURL:sourceURL start:0 end:-1 callback:^(NSData *fileData, NSString *mimeType, CDVFileError err) {
+ if (err) {
+ // We couldn't find the asset. Send the appropriate error.
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ } else {
+ [self uploadData:fileData command:command];
+ }
+ }];
+ return;
+ } else {
+ // Extract the path part out of a file: URL.
+ NSString* filePath = [source hasPrefix:@"/"] ? [source copy] : [(NSURL *)[NSURL URLWithString:source] path];
+ if (filePath == nil) {
+ // We couldn't find the asset. Send the appropriate error.
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return;
+ }
+
+ // Memory map the file so that it can be read efficiently even if it is large.
+ NSData* fileData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&err];
+
+ if (err != nil) {
+ NSLog(@"Error opening file %@: %@", source, err);
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ } else {
+ [self uploadData:fileData command:command];
+ }
+ }
+}
+
+- (void)upload:(CDVInvokedUrlCommand*)command
+{
+ // fileData and req are split into helper functions to ease the unit testing of delegateForUpload.
+ // First, get the file data. This method will call `uploadData:command`.
+ [self fileDataForUploadCommand:command];
+}
+
+- (void)uploadData:(NSData*)fileData command:(CDVInvokedUrlCommand*)command
+{
+ NSURLRequest* req = [self requestForUploadCommand:command fileData:fileData];
+
+ if (req == nil) {
+ return;
+ }
+ CDVFileTransferDelegate* delegate = [self delegateForUploadCommand:command];
+ delegate.connection = [[NSURLConnection alloc] initWithRequest:req delegate:delegate startImmediately:NO];
+ if (self.queue == nil) {
+ self.queue = [[NSOperationQueue alloc] init];
+ }
+ [delegate.connection setDelegateQueue:self.queue];
+
+ // sets a background task ID for the transfer object.
+ delegate.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
+ [delegate cancelTransfer:delegate.connection];
+ }];
+
+ @synchronized (activeTransfers) {
+ activeTransfers[delegate.objectId] = delegate;
+ }
+ [delegate.connection start];
+}
+
+- (void)abort:(CDVInvokedUrlCommand*)command
+{
+ NSString* objectId = [command argumentAtIndex:0];
+
+ @synchronized (activeTransfers) {
+ CDVFileTransferDelegate* delegate = activeTransfers[objectId];
+ if (delegate != nil) {
+ [delegate cancelTransfer:delegate.connection];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:CONNECTION_ABORTED AndSource:delegate.source AndTarget:delegate.target]];
+ [self.commandDelegate sendPluginResult:result callbackId:delegate.callbackId];
+ }
+ }
+}
+
+- (void)download:(CDVInvokedUrlCommand*)command
+{
+ DLog(@"File Transfer downloading file...");
+ NSString* source = [command argumentAtIndex:0];
+ NSString* target = [command argumentAtIndex:1];
+ BOOL trustAllHosts = [[command argumentAtIndex:2 withDefault:[NSNumber numberWithBool:NO]] boolValue]; // allow self-signed certs
+ NSString* objectId = [command argumentAtIndex:3];
+ NSDictionary* headers = [command argumentAtIndex:4 withDefault:nil];
+
+ CDVPluginResult* result = nil;
+ CDVFileTransferError errorCode = 0;
+
+ NSURL* targetURL;
+
+ if ([target hasPrefix:@"/"]) {
+ /* Backwards-compatibility:
+ * Check here to see if it looks like the user passed in a raw filesystem path. (Perhaps they had the path saved, and were previously using it with the old version of File). If so, normalize it by removing empty path segments, and check with File to see if any of the installed filesystems will handle it. If so, then we will end up with a filesystem url to use for the remainder of this operation.
+ */
+ target = [target stringByReplacingOccurrencesOfString:@"//" withString:@"/"];
+ targetURL = [[self.commandDelegate getCommandInstance:@"File"] fileSystemURLforLocalPath:target].url;
+ } else {
+ targetURL = [NSURL URLWithString:target];
+ }
+
+ NSURL* sourceURL = [NSURL URLWithString:source];
+
+ if (!sourceURL) {
+ errorCode = INVALID_URL_ERR;
+ NSLog(@"File Transfer Error: Invalid server URL %@", source);
+ } else if (![targetURL isFileURL]) {
+ CDVFilesystemURL *fsURL = [CDVFilesystemURL fileSystemURLWithString:target];
+ if (!fsURL) {
+ errorCode = FILE_NOT_FOUND_ERR;
+ NSLog(@"File Transfer Error: Invalid file path or URL %@", target);
+ }
+ }
+
+ if (errorCode > 0) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:errorCode AndSource:source AndTarget:target]];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return;
+ }
+
+ NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:sourceURL];
+ [self applyRequestHeaders:headers toRequest:req];
+
+ CDVFileTransferDelegate* delegate = [[CDVFileTransferDelegate alloc] init];
+ delegate.command = self;
+ delegate.direction = CDV_TRANSFER_DOWNLOAD;
+ delegate.callbackId = command.callbackId;
+ delegate.objectId = objectId;
+ delegate.source = source;
+ delegate.target = [targetURL absoluteString];
+ delegate.targetURL = targetURL;
+ delegate.trustAllHosts = trustAllHosts;
+ delegate.filePlugin = [self.commandDelegate getCommandInstance:@"File"];
+ delegate.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
+ [delegate cancelTransfer:delegate.connection];
+ }];
+
+ delegate.connection = [[NSURLConnection alloc] initWithRequest:req delegate:delegate startImmediately:NO];
+
+ if (self.queue == nil) {
+ self.queue = [[NSOperationQueue alloc] init];
+ }
+ [delegate.connection setDelegateQueue:self.queue];
+
+ @synchronized (activeTransfers) {
+ activeTransfers[delegate.objectId] = delegate;
+ }
+ // Downloads can take time
+ // sending this to a new thread calling the download_async method
+ dispatch_async(
+ dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL),
+ ^(void) { [delegate.connection start];}
+ );
+}
+
+- (NSMutableDictionary*)createFileTransferError:(int)code AndSource:(NSString*)source AndTarget:(NSString*)target
+{
+ NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:3];
+
+ [result setObject:[NSNumber numberWithInt:code] forKey:@"code"];
+ if (source != nil) {
+ [result setObject:source forKey:@"source"];
+ }
+ if (target != nil) {
+ [result setObject:target forKey:@"target"];
+ }
+ NSLog(@"FileTransferError %@", result);
+
+ return result;
+}
+
+- (NSMutableDictionary*)createFileTransferError:(int)code
+ AndSource:(NSString*)source
+ AndTarget:(NSString*)target
+ AndHttpStatus:(int)httpStatus
+ AndBody:(NSString*)body
+{
+ NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:5];
+
+ [result setObject:[NSNumber numberWithInt:code] forKey:@"code"];
+ if (source != nil) {
+ [result setObject:source forKey:@"source"];
+ }
+ if (target != nil) {
+ [result setObject:target forKey:@"target"];
+ }
+ [result setObject:[NSNumber numberWithInt:httpStatus] forKey:@"http_status"];
+ if (body != nil) {
+ [result setObject:body forKey:@"body"];
+ }
+ NSLog(@"FileTransferError %@", result);
+
+ return result;
+}
+
+- (void)onReset {
+ @synchronized (activeTransfers) {
+ while ([activeTransfers count] > 0) {
+ CDVFileTransferDelegate* delegate = [activeTransfers allValues][0];
+ [delegate cancelTransfer:delegate.connection];
+ }
+ }
+}
+
+@end
+
+@interface CDVFileTransferEntityLengthRequest : NSObject {
+ NSURLConnection* _connection;
+ CDVFileTransferDelegate* __weak _originalDelegate;
+}
+
+- (CDVFileTransferEntityLengthRequest*)initWithOriginalRequest:(NSURLRequest*)originalRequest andDelegate:(CDVFileTransferDelegate*)originalDelegate;
+
+@end
+
+@implementation CDVFileTransferEntityLengthRequest
+
+- (CDVFileTransferEntityLengthRequest*)initWithOriginalRequest:(NSURLRequest*)originalRequest andDelegate:(CDVFileTransferDelegate*)originalDelegate
+{
+ if (self) {
+ DLog(@"Requesting entity length for GZIPped content...");
+
+ NSMutableURLRequest* req = [originalRequest mutableCopy];
+ [req setHTTPMethod:@"HEAD"];
+ [req setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
+
+ _originalDelegate = originalDelegate;
+ _connection = [NSURLConnection connectionWithRequest:req delegate:self];
+ }
+ return self;
+}
+
+- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
+{
+ DLog(@"HEAD request returned; content-length is %lld", [response expectedContentLength]);
+ [_originalDelegate updateBytesExpected:[response expectedContentLength]];
+}
+
+- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
+{}
+
+- (void)connectionDidFinishLoading:(NSURLConnection*)connection
+{}
+
+@end
+
+@implementation CDVFileTransferDelegate
+
+@synthesize callbackId, connection = _connection, source, target, responseData, responseHeaders, command, bytesTransfered, bytesExpected, direction, responseCode, objectId, targetFileHandle, filePlugin;
+
+- (void)connectionDidFinishLoading:(NSURLConnection*)connection
+{
+ NSString* uploadResponse = nil;
+ NSString* downloadResponse = nil;
+ NSMutableDictionary* uploadResult;
+ CDVPluginResult* result = nil;
+
+ NSLog(@"File Transfer Finished with response code %d", self.responseCode);
+
+ if (self.direction == CDV_TRANSFER_UPLOAD) {
+ uploadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
+
+ if ((self.responseCode >= 200) && (self.responseCode < 300)) {
+ // create dictionary to return FileUploadResult object
+ uploadResult = [NSMutableDictionary dictionaryWithCapacity:3];
+ if (uploadResponse != nil) {
+ [uploadResult setObject:uploadResponse forKey:@"response"];
+ [uploadResult setObject:self.responseHeaders forKey:@"headers"];
+ }
+ [uploadResult setObject:[NSNumber numberWithLongLong:self.bytesTransfered] forKey:@"bytesSent"];
+ [uploadResult setObject:[NSNumber numberWithInt:self.responseCode] forKey:@"responseCode"];
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:uploadResult];
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:CONNECTION_ERR AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:uploadResponse]];
+ }
+ }
+ if (self.direction == CDV_TRANSFER_DOWNLOAD) {
+ if (self.targetFileHandle) {
+ [self.targetFileHandle closeFile];
+ self.targetFileHandle = nil;
+ DLog(@"File Transfer Download success");
+
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self.filePlugin makeEntryForURL:self.targetURL]];
+ } else {
+ downloadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
+ CDVFileTransferError errorCode = self.responseCode == 404 ? FILE_NOT_FOUND_ERR
+ : (self.responseCode == 304 ? NOT_MODIFIED : CONNECTION_ERR);
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:errorCode AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:downloadResponse]];
+ }
+ }
+
+ [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
+
+ // remove connection for activeTransfers
+ @synchronized (command.activeTransfers) {
+ [command.activeTransfers removeObjectForKey:objectId];
+ // remove background id task in case our upload was done in the background
+ [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
+ self.backgroundTaskID = UIBackgroundTaskInvalid;
+ }
+}
+
+- (void)removeTargetFile
+{
+ NSFileManager* fileMgr = [NSFileManager defaultManager];
+
+ NSString *targetPath = [self targetFilePath];
+ if ([fileMgr fileExistsAtPath:targetPath])
+ {
+ [fileMgr removeItemAtPath:targetPath error:nil];
+ }
+}
+
+- (void)cancelTransfer:(NSURLConnection*)connection
+{
+ [connection cancel];
+ @synchronized (self.command.activeTransfers) {
+ CDVFileTransferDelegate* delegate = self.command.activeTransfers[self.objectId];
+ [self.command.activeTransfers removeObjectForKey:self.objectId];
+ [[UIApplication sharedApplication] endBackgroundTask:delegate.backgroundTaskID];
+ delegate.backgroundTaskID = UIBackgroundTaskInvalid;
+ }
+
+ [self removeTargetFile];
+}
+
+- (void)cancelTransferWithError:(NSURLConnection*)connection errorMessage:(NSString*)errorMessage
+{
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsDictionary:[self.command createFileTransferError:FILE_NOT_FOUND_ERR AndSource:self.source AndTarget:self.target AndHttpStatus:self.responseCode AndBody:errorMessage]];
+
+ NSLog(@"File Transfer Error: %@", errorMessage);
+ [self cancelTransfer:connection];
+ [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
+}
+
+- (NSString *)targetFilePath
+{
+ NSString *path = nil;
+ CDVFilesystemURL *sourceURL = [CDVFilesystemURL fileSystemURLWithString:self.target];
+ if (sourceURL && sourceURL.fileSystemName != nil) {
+ // This requires talking to the current CDVFile plugin
+ NSObject *fs = [self.filePlugin filesystemForURL:sourceURL];
+ path = [fs filesystemPathForURL:sourceURL];
+ } else {
+ // Extract the path part out of a file: URL.
+ path = [self.target hasPrefix:@"/"] ? [self.target copy] : [(NSURL *)[NSURL URLWithString:self.target] path];
+ }
+ return path;
+}
+
+- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
+{
+ NSError* __autoreleasing error = nil;
+
+ self.mimeType = [response MIMEType];
+ self.targetFileHandle = nil;
+
+ // required for iOS 4.3, for some reason; response is
+ // a plain NSURLResponse, not the HTTP subclass
+ if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
+ NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
+
+ self.responseCode = (int)[httpResponse statusCode];
+ self.bytesExpected = [response expectedContentLength];
+ self.responseHeaders = [httpResponse allHeaderFields];
+ if ((self.direction == CDV_TRANSFER_DOWNLOAD) && (self.responseCode == 200) && (self.bytesExpected == NSURLResponseUnknownLength)) {
+ // Kick off HEAD request to server to get real length
+ // bytesExpected will be updated when that response is returned
+ self.entityLengthRequest = [[CDVFileTransferEntityLengthRequest alloc] initWithOriginalRequest:connection.currentRequest andDelegate:self];
+ }
+ } else if ([response.URL isFileURL]) {
+ NSDictionary* attr = [[NSFileManager defaultManager] attributesOfItemAtPath:[response.URL path] error:nil];
+ self.responseCode = 200;
+ self.bytesExpected = [attr[NSFileSize] longLongValue];
+ } else {
+ self.responseCode = 200;
+ self.bytesExpected = NSURLResponseUnknownLength;
+ }
+ if ((self.direction == CDV_TRANSFER_DOWNLOAD) && (self.responseCode >= 200) && (self.responseCode < 300)) {
+ // Download response is okay; begin streaming output to file
+ NSString *filePath = [self targetFilePath];
+ if (filePath == nil) {
+ // We couldn't find the asset. Send the appropriate error.
+ [self cancelTransferWithError:connection errorMessage:[NSString stringWithFormat:@"Could not create target file"]];
+ return;
+ }
+
+ NSString* parentPath = [filePath stringByDeletingLastPathComponent];
+
+ // create parent directories if needed
+ if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
+ if (error) {
+ [self cancelTransferWithError:connection errorMessage:[NSString stringWithFormat:@"Could not create path to save downloaded file: %@", [error localizedDescription]]];
+ } else {
+ [self cancelTransferWithError:connection errorMessage:@"Could not create path to save downloaded file"];
+ }
+ return;
+ }
+ // create target file
+ if ([[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil] == NO) {
+ [self cancelTransferWithError:connection errorMessage:@"Could not create target file"];
+ return;
+ }
+ // open target file for writing
+ self.targetFileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
+ if (self.targetFileHandle == nil) {
+ [self cancelTransferWithError:connection errorMessage:@"Could not open target file for writing"];
+ }
+ DLog(@"Streaming to file %@", filePath);
+ }
+}
+
+- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
+{
+ NSString* body = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:CONNECTION_ERR AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:body]];
+
+ NSLog(@"File Transfer Error: %@", [error localizedDescription]);
+
+ [self cancelTransfer:connection];
+ [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
+}
+
+- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
+{
+ self.bytesTransfered += data.length;
+ if (self.targetFileHandle) {
+ [self.targetFileHandle writeData:data];
+ } else {
+ [self.responseData appendData:data];
+ }
+ [self updateProgress];
+}
+
+- (void)updateBytesExpected:(long long)newBytesExpected
+{
+ DLog(@"Updating bytesExpected to %lld", newBytesExpected);
+ self.bytesExpected = newBytesExpected;
+ [self updateProgress];
+}
+
+- (void)updateProgress
+{
+ if (self.direction == CDV_TRANSFER_DOWNLOAD) {
+ BOOL lengthComputable = (self.bytesExpected != NSURLResponseUnknownLength);
+ // If the response is GZipped, and we have an outstanding HEAD request to get
+ // the length, then hold off on sending progress events.
+ if (!lengthComputable && (self.entityLengthRequest != nil)) {
+ return;
+ }
+ NSMutableDictionary* downloadProgress = [NSMutableDictionary dictionaryWithCapacity:3];
+ [downloadProgress setObject:[NSNumber numberWithBool:lengthComputable] forKey:@"lengthComputable"];
+ [downloadProgress setObject:[NSNumber numberWithLongLong:self.bytesTransfered] forKey:@"loaded"];
+ [downloadProgress setObject:[NSNumber numberWithLongLong:self.bytesExpected] forKey:@"total"];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:downloadProgress];
+ [result setKeepCallbackAsBool:true];
+ [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+}
+
+- (void)connection:(NSURLConnection*)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
+{
+ if (self.direction == CDV_TRANSFER_UPLOAD) {
+ NSMutableDictionary* uploadProgress = [NSMutableDictionary dictionaryWithCapacity:3];
+
+ [uploadProgress setObject:[NSNumber numberWithBool:true] forKey:@"lengthComputable"];
+ [uploadProgress setObject:[NSNumber numberWithLongLong:totalBytesWritten] forKey:@"loaded"];
+ [uploadProgress setObject:[NSNumber numberWithLongLong:totalBytesExpectedToWrite] forKey:@"total"];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:uploadProgress];
+ [result setKeepCallbackAsBool:true];
+ [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }
+ self.bytesTransfered = totalBytesWritten;
+}
+
+// for self signed certificates
+- (void)connection:(NSURLConnection*)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
+{
+ if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
+ if (self.trustAllHosts) {
+ NSURLCredential* credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+ [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
+ }
+ [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
+ } else {
+ [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
+ }
+}
+
+- (id)init
+{
+ if ((self = [super init])) {
+ self.responseData = [NSMutableData data];
+ self.targetFileHandle = nil;
+ }
+ return self;
+}
+
+@end
diff --git a/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp b/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp
new file mode 100644
index 0000000..5b1adea
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.cpp
@@ -0,0 +1,265 @@
+/*
+ *
+ * Copyright 2013 Canonical Ltd.
+ *
+ * Licensed 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.
+ *
+*/
+
+#include "file-transfer.h"
+#include
+#include
+
+static void SetHeaders(QNetworkRequest &request, const QVariantMap &headers) {
+ for (const QString &key: headers.keys()) {
+ QVariant val = *headers.find(key);
+ QString value = val.toString();
+ if (val.userType() == QMetaType::QVariantList || val.userType() == QMetaType::QStringList) {
+ QList list = val.toList();
+ for (QVariant v: list) {
+ if (value.size())
+ value += ", ";
+ value += v.toString();
+ }
+ }
+ request.setRawHeader(key.toUtf8(), value.toUtf8());
+ }
+}
+
+void FileTransfer::download(int scId, int ecId, const QString& url, const QString &target, bool /*trustAllHost*/, int id, const QVariantMap &headers) {
+ QSharedPointer request(new FileTransferRequest(_manager, scId, ecId, id, this));
+
+ assert(_id2request.find(id) == _id2request.end());
+
+ _id2request.insert(id, request);
+
+ request->connect(request.data(), &FileTransferRequest::done, [&]() {
+ auto it = _id2request.find(id);
+ while (it != _id2request.end() && it.key() == id) {
+ if (it.value().data() == request.data()) {
+ _id2request.erase(it);
+ break;
+ }
+ it++;
+ }
+ });
+ request->download(url, target, headers);
+}
+
+void FileTransfer::upload(int scId, int ecId, const QString &fileURI, const QString& url, const QString& fileKey, const QString& fileName, const QString& mimeType,
+ const QVariantMap & params, bool /*trustAllHosts*/, bool /*chunkedMode*/, const QVariantMap &headers, int id, const QString &/*httpMethod*/) {
+ QSharedPointer request(new FileTransferRequest(_manager, scId, ecId, id, this));
+
+ assert(_id2request.find(id) == _id2request.end());
+
+ _id2request.insert(id, request);
+
+ request->connect(request.data(), &FileTransferRequest::done, [&]() {
+ auto it = _id2request.find(id);
+ while (it != _id2request.end() && it.key() == id) {
+ if (it.value().data() == request.data()) {
+ _id2request.erase(it);
+ break;
+ }
+ it++;
+ }
+ });
+ request->upload(url, fileURI, fileKey, fileName, mimeType, params, headers);
+}
+
+void FileTransfer::abort(int scId, int ecId, int id) {
+ Q_UNUSED(scId)
+ Q_UNUSED(ecId)
+
+ auto it = _id2request.find(id);
+ while (it != _id2request.end() && it.key() == id) {
+ (*it)->abort();
+ it++;
+ }
+}
+
+void FileTransferRequest::download(const QString& uri, const QString &targetURI, const QVariantMap &headers) {
+ QUrl url(uri);
+ QNetworkRequest request;
+
+ QSharedPointer filePlugin(_plugin->cordova()->getPlugin());
+
+ if (!filePlugin.data())
+ return;
+
+ if (!url.isValid()) {
+ QVariantMap map;
+ map.insert("code", INVALID_URL_ERR);
+ map.insert("source", uri);
+ map.insert("target", targetURI);
+ _plugin->cb(_ecId, map);
+ emit done();
+ return;
+ }
+
+ request.setUrl(url);
+ if (url.password().size() || url.userName().size()) {
+ QString headerData = "Basic " + (url.userName() + ":" + url.password()).toLocal8Bit().toBase64();
+ request.setRawHeader("Authorization", headerData.toLocal8Bit());
+ }
+ SetHeaders(request, headers);
+ _reply = QSharedPointer(_manager.get(request));
+
+ _reply->connect(_reply.data(), &QNetworkReply::finished, [this, targetURI, uri, filePlugin]() {
+ if (!_scId || _reply->error() != QNetworkReply::NoError)
+ return;
+
+ QPair f1(dynamic_cast(filePlugin.data())->resolveURI(targetURI));
+
+ QFile res(f1.second.absoluteFilePath());
+ if (!f1.first || !res.open(QIODevice::WriteOnly)) {
+ QVariantMap map;
+ map.insert("code", INVALID_URL_ERR);
+ map.insert("source", uri);
+ map.insert("target", targetURI);
+ _plugin->cb(_ecId, map);
+ emit done();
+ return;
+ }
+ res.write(_reply->readAll());
+
+ _plugin->cb(_scId, dynamic_cast(filePlugin.data())->file2map(f1.second));
+
+ emit done();
+ });
+ _reply->connect(_reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError)));
+ _reply->connect(_reply.data(), SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(progress(qint64, qint64)));
+}
+
+void FileTransferRequest::upload(const QString& _url, const QString& fileURI, QString fileKey, QString fileName, QString mimeType, const QVariantMap ¶ms, const QVariantMap &headers) {
+ QUrl url(_url);
+ QNetworkRequest request;
+
+ QSharedPointer filePlugin(_plugin->cordova()->getPlugin());
+
+ if (!filePlugin.data())
+ return;
+
+ if (!url.isValid()) {
+ QVariantMap map;
+ map.insert("code", INVALID_URL_ERR);
+ map.insert("source", fileURI);
+ map.insert("target", _url);
+ _plugin->cb(_ecId, map);
+ emit done();
+ return;
+ }
+
+ QPair f1(dynamic_cast(filePlugin.data())->resolveURI(fileURI));
+ QFile file(f1.second.absoluteFilePath());
+ if (!f1.first || !file.open(QIODevice::ReadOnly)) {
+ QVariantMap map;
+ map.insert("code", FILE_NOT_FOUND_ERR);
+ map.insert("source", fileURI);
+ map.insert("target", _url);
+ _plugin->cb(_ecId, map);
+ emit done();
+ return;
+ }
+ QString content{file.readAll()};
+
+ request.setUrl(url);
+ if (url.password().size() || url.userName().size()) {
+ QString headerData = "Basic " + (url.userName() + ":" + url.password()).toLocal8Bit().toBase64();
+ request.setRawHeader("Authorization", headerData.toLocal8Bit());
+ }
+ SetHeaders(request, headers);
+
+ QString boundary = QString("CORDOVA-QT-%1A").arg(qrand());
+ while (content.contains(boundary)) {
+ boundary += QString("B%1A").arg(qrand());
+ }
+
+ request.setHeader(QNetworkRequest::ContentTypeHeader, QString("multipart/form-data; boundary=") + boundary);
+
+ fileKey.replace("\"", "");
+ fileName.replace("\"", "");
+ mimeType.replace("\"", "");
+ QString part = "--" + boundary + "\r\n";
+
+ part += "Content-Disposition: form-data; name=\"" + fileKey +"\"; filename=\"" + fileName + "\"\r\n";
+ part += "Content-Type: " + mimeType + "\r\n\r\n";
+ part += content + "\r\n";
+
+ for (QString key: params.keys()) {
+ part += "--" + boundary + "\r\n";
+ part += "Content-Disposition: form-data; name=\"" + key + "\";\r\n\r\n";
+ part += params.find(key)->toString();
+ part += "\r\n";
+ }
+
+ part += QString("--") + boundary + "--" + "\r\n";
+
+ _reply = QSharedPointer(_manager.post(request, QByteArray(part.toUtf8())));
+
+ _reply->connect(_reply.data(), &QNetworkReply::finished, [this, content]() {
+ if (_reply->error() != QNetworkReply::NoError)
+ return;
+ int status = 200;
+ QVariant statusCode = _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
+
+ if (statusCode.isValid()) {
+ status = statusCode.toInt();
+ }
+
+ QVariantMap map;
+ map.insert("responseCode", status);
+ map.insert("response", QString(_reply->readAll()));
+ map.insert("bytesSent", content.size());
+ _plugin->cb(_scId, map);
+ emit done();
+ });
+ _reply->connect(_reply.data(), SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError)));
+ _reply->connect(_reply.data(), SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(progress(qint64, qint64)));
+}
+
+void FileTransferRequest::abort() {
+ QVariantMap map;
+ map.insert("code", ABORT_ERR);
+ _plugin->cb(_ecId, map);
+ _scId = 0;
+ emit done();
+}
+
+void FileTransferRequest::error(QNetworkReply::NetworkError code) {
+ Q_UNUSED(code);
+
+ int status = 404;
+ QVariant statusCode = _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
+ if (statusCode.isValid()) {
+ status = statusCode.toInt();
+ }
+
+ QVariantMap map;
+ map.insert("http_status", status);
+ map.insert("body", QString(_reply->readAll()));
+ map.insert("code", CONNECTION_ERR);
+ _plugin->cb(_ecId, map);
+ emit done();
+}
+
+void FileTransferRequest::progress(qint64 bytesReceived, qint64 bytesTotal) {
+ QVariantMap map;
+ map.insert("lengthComputable", true);
+ map.insert("total", bytesTotal);
+ map.insert("loaded", bytesReceived);
+
+ if (bytesReceived && bytesTotal && _scId)
+ _plugin->callbackWithoutRemove(_scId, CordovaInternal::format(map));
+}
diff --git a/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h b/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h
new file mode 100644
index 0000000..75822cb
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/ubuntu/file-transfer.h
@@ -0,0 +1,103 @@
+/*
+ *
+ * Copyright 2013 Canonical Ltd.
+ *
+ * Licensed 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.
+ *
+*/
+
+#ifndef FILE_TRANSFER_H_SDASDASDAS
+#define FILE_TRANSFER_H_SDASDASDAS
+
+#include
+#include
+
+#include
+
+class FileTransfer;
+
+class FileTransferRequest: public QObject {
+ Q_OBJECT
+
+ QNetworkAccessManager &_manager;
+ int _scId, _ecId;
+ int _id;
+ QSharedPointer _reply;
+
+ enum FileTransferError {
+ FILE_NOT_FOUND_ERR = 1,
+ INVALID_URL_ERR = 2,
+ CONNECTION_ERR = 3,
+ ABORT_ERR = 4
+ };
+
+public:
+ FileTransferRequest(QNetworkAccessManager &manager, int scId, int ecId, int id, FileTransfer *plugin):
+ _manager(manager),
+ _scId(scId),
+ _ecId(ecId),
+ _id(id),
+ _plugin(plugin) {
+ }
+
+ void download(const QString& url, const QString &targetURI, const QVariantMap &headers);
+ void upload(const QString& _url, const QString& fileURI, QString fileKey, QString fileName, QString mimeType, const QVariantMap ¶ms, const QVariantMap &headers);
+ void abort();
+
+signals:
+ void done();
+
+private slots:
+ void progress(qint64 bytesReceived, qint64 bytesTotal);
+ void error(QNetworkReply::NetworkError code);
+private:
+ FileTransfer *_plugin;
+ Q_DISABLE_COPY(FileTransferRequest);
+};
+
+class FileTransfer : public CPlugin {
+ Q_OBJECT
+public:
+ explicit FileTransfer(Cordova *cordova): CPlugin(cordova) {
+ }
+
+ Cordova* cordova() {
+ return m_cordova;
+ }
+
+ virtual const QString fullName() override {
+ return FileTransfer::fullID();
+ }
+
+ virtual const QString shortName() override {
+ return "FileTransfer";
+ }
+
+ static const QString fullID() {
+ return "FileTransfer";
+ }
+
+public slots:
+ void abort(int scId, int ecId, int id);
+ void download(int scId, int ecId, const QString& url, const QString &target, bool /*trustAllHost*/, int id, const QVariantMap &/*headers*/);
+ void upload(int scId, int ecId, const QString &filePath, const QString& url, const QString& fileKey, const QString& fileName, const QString& mimeType,
+ const QVariantMap & params, bool /*trustAllHosts*/, bool /*chunkedMode*/, const QVariantMap &headers, int id, const QString &httpMethod);
+
+private:
+ QNetworkAccessManager _manager;
+ QMultiMap > _id2request;
+ int lastRequestId;
+};
+
+#endif
diff --git a/plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js b/plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js
new file mode 100644
index 0000000..d9e884e
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/windows/FileTransferProxy.js
@@ -0,0 +1,425 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+/*jshint -W030 */
+/*global Windows, WinJS*/
+/*global module, require*/
+
+var FTErr = require('./FileTransferError'),
+ 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;
+
+
+// Some private helper functions, hidden by the module
+function cordovaPathToNative(path) {
+
+ var cleanPath = String(path);
+ // turn / into \\
+ cleanPath = cleanPath.replace(/\//g, '\\');
+ // turn \\ into \
+ cleanPath = cleanPath.replace(/\\\\/g, '\\');
+ // strip end \\ characters
+ cleanPath = cleanPath.replace(/\\+$/g, '');
+ return cleanPath;
+}
+
+function nativePathToCordova(path) {
+ return String(path).replace(/\\/g, '/');
+}
+
+var fileTransferOps = [];
+
+function FileTransferOperation(state, promise) {
+ this.state = state;
+ this.promise = promise;
+}
+
+FileTransferOperation.PENDING = 0;
+FileTransferOperation.DONE = 1;
+FileTransferOperation.CANCELLED = 2;
+
+var HTTP_E_STATUS_NOT_MODIFIED = -2145844944;
+
+module.exports = {
+
+/*
+exec(win, fail, 'FileTransfer', 'upload',
+[filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+*/
+ upload:function(successCallback, errorCallback, options) {
+ var filePath = options[0];
+ var server = options[1];
+ var fileKey = options[2] || 'source';
+ var fileName = options[3];
+ var mimeType = options[4];
+ var params = options[5];
+ // var trustAllHosts = options[6]; // todo
+ // var chunkedMode = options[7]; // todo
+ var headers = options[8] || {};
+ var uploadId = options[9];
+ var httpMethod = options[10];
+
+ if (!filePath || (typeof filePath !== 'string')) {
+ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR,null,server));
+ return;
+ }
+
+ if (filePath.substr(0, 8) === "file:///") {
+ filePath = appData.localFolder.path + filePath.substr(8).split("/").join("\\");
+ } else if (filePath.indexOf('ms-appdata:///') === 0) {
+ // Handle 'ms-appdata' scheme
+ filePath = filePath.replace('ms-appdata:///local', appData.localFolder.path)
+ .replace('ms-appdata:///temp', appData.temporaryFolder.path);
+ } else if (filePath.indexOf('cdvfile://') === 0) {
+ filePath = filePath.replace('cdvfile://localhost/persistent', appData.localFolder.path)
+ .replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
+ }
+ // normalize path separators
+ filePath = cordovaPathToNative(filePath);
+
+ // Create internal download operation object
+ fileTransferOps[uploadId] = new FileTransferOperation(FileTransferOperation.PENDING, null);
+
+ Windows.Storage.StorageFile.getFileFromPathAsync(filePath)
+ .then(function (storageFile) {
+
+ if(!fileName) {
+ fileName = storageFile.name;
+ }
+ if(!mimeType) {
+ // use the actual content type of the file, probably this should be the default way.
+ // other platforms probably can't look this up.
+ mimeType = storageFile.contentType;
+ }
+
+ // check if download isn't already cancelled
+ var uploadOp = fileTransferOps[uploadId];
+ if (uploadOp && uploadOp.state === FileTransferOperation.CANCELLED) {
+ // Here we should call errorCB with ABORT_ERR error
+ errorCallback(new FTErr(FTErr.ABORT_ERR, nativePathToCordova(filePath), server));
+ return;
+ }
+
+ // setting request headers for uploader
+ var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader();
+ uploader.method = httpMethod;
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ uploader.setRequestHeader(header, headers[header]);
+ }
+ }
+
+ // adding params supplied to request payload
+ var transferParts = [];
+ for (var key in params) {
+ if (params.hasOwnProperty(key)) {
+ var contentPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart();
+ contentPart.setHeader("Content-Disposition", "form-data; name=\"" + key + "\"");
+ contentPart.setText(params[key]);
+ transferParts.push(contentPart);
+ }
+ }
+
+ // Adding file to upload to request payload
+ var fileToUploadPart = new Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart(fileKey, fileName);
+ fileToUploadPart.setFile(storageFile);
+ transferParts.push(fileToUploadPart);
+
+ // create download object. This will throw an exception if URL is malformed
+ var uri = new Windows.Foundation.Uri(server);
+ try {
+ uploader.createUploadAsync(uri, transferParts).then(
+ function (upload) {
+ // update internal TransferOperation object with newly created promise
+ var uploadOperation = upload.startAsync();
+ fileTransferOps[uploadId].promise = uploadOperation;
+
+ uploadOperation.then(
+ function (result) {
+ // Update TransferOperation object with new state, delete promise property
+ // since it is not actual anymore
+ var currentUploadOp = fileTransferOps[uploadId];
+ if (currentUploadOp) {
+ currentUploadOp.state = FileTransferOperation.DONE;
+ currentUploadOp.promise = null;
+ }
+
+ var response = result.getResponseInformation();
+ 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) {
+ ftResult.response = reader.readString(size);
+ successCallback(ftResult);
+ reader.close();
+ });
+ },
+ function (error) {
+ var source = nativePathToCordova(filePath);
+
+ // Handle download error here.
+ // Wrap this routines into promise due to some async methods
+ var getTransferError = new WinJS.Promise(function(resolve) {
+ if (error.message === 'Canceled') {
+ // If download was cancelled, message property will be specified
+ resolve(new FTErr(FTErr.ABORT_ERR, source, server, null, null, error));
+ } else {
+ // in the other way, try to get response property
+ var response = upload.getResponseInformation();
+ if (!response) {
+ resolve(new FTErr(FTErr.CONNECTION_ERR, source, server));
+ } else {
+ var reader = new Windows.Storage.Streams.DataReader(upload.getResultStreamAt(0));
+ reader.loadAsync(upload.progress.bytesReceived).then(function (size) {
+ var responseText = reader.readString(size);
+ resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, server, response.statusCode, responseText, error));
+ reader.close();
+ });
+ }
+ }
+ });
+
+ // Update TransferOperation object with new state, delete promise property
+ // since it is not actual anymore
+ var currentUploadOp = fileTransferOps[uploadId];
+ if (currentUploadOp) {
+ currentUploadOp.state = FileTransferOperation.CANCELLED;
+ currentUploadOp.promise = null;
+ }
+
+ // Cleanup, remove incompleted file
+ getTransferError.then(function(transferError) {
+ storageFile.deleteAsync().then(function() {
+ errorCallback(transferError);
+ });
+ });
+ },
+ function (evt) {
+ var progressEvent = new ProgressEvent('progress', {
+ loaded: evt.progress.bytesSent,
+ total: evt.progress.totalBytesToSend,
+ target: evt.resultFile
+ });
+ progressEvent.lengthComputable = true;
+ successCallback(progressEvent, { keepCallback: true });
+ }
+ );
+ },
+ function (err) {
+ var errorObj = new FTErr(FTErr.INVALID_URL_ERR);
+ errorObj.exception = err;
+ errorCallback(errorObj);
+ }
+ );
+ } catch (e) {
+ errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
+ }
+ }, function(err) {
+ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, server, server, null, null, err));
+ });
+ },
+
+ // [source, target, trustAllHosts, id, headers]
+ download:function(successCallback, errorCallback, options) {
+ var source = options[0];
+ var target = options[1];
+ var downloadId = options[3];
+ var headers = options[4] || {};
+
+ if (!target) {
+ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR));
+ return;
+ }
+ if (target.substr(0, 8) === "file:///") {
+ target = appData.localFolder.path + target.substr(8).split("/").join("\\");
+ } else if (target.indexOf('ms-appdata:///') === 0) {
+ // Handle 'ms-appdata' scheme
+ target = target.replace('ms-appdata:///local', appData.localFolder.path)
+ .replace('ms-appdata:///temp', appData.temporaryFolder.path);
+ } else if (target.indexOf('cdvfile://') === 0) {
+ target = target.replace('cdvfile://localhost/persistent', appData.localFolder.path)
+ .replace('cdvfile://localhost/temporary', appData.temporaryFolder.path);
+ }
+ target = cordovaPathToNative(target);
+
+ var path = target.substr(0, target.lastIndexOf("\\"));
+ var fileName = target.substr(target.lastIndexOf("\\") + 1);
+ if (path === null || fileName === null) {
+ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR));
+ return;
+ }
+
+ var download = null;
+
+ // Create internal download operation object
+ fileTransferOps[downloadId] = new FileTransferOperation(FileTransferOperation.PENDING, null);
+
+ var downloadCallback = function(storageFolder) {
+ storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.replaceExisting).then(function(storageFile) {
+
+ // check if download isn't already cancelled
+ var downloadOp = fileTransferOps[downloadId];
+ if (downloadOp && downloadOp.state === FileTransferOperation.CANCELLED) {
+ // Here we should call errorCB with ABORT_ERR error
+ errorCallback(new FTErr(FTErr.ABORT_ERR, source, target));
+ return;
+ }
+
+ // if download isn't cancelled, contunue with creating and preparing download operation
+ var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ downloader.setRequestHeader(header, headers[header]);
+ }
+ }
+
+ // create download object. This will throw an exception if URL is malformed
+ try {
+ var uri = Windows.Foundation.Uri(source);
+ download = downloader.createDownload(uri, storageFile);
+ } catch (e) {
+ // so we handle this and call errorCallback
+ errorCallback(new FTErr(FTErr.INVALID_URL_ERR));
+ return;
+ }
+
+ var downloadOperation = download.startAsync();
+ // update internal TransferOperation object with newly created promise
+ fileTransferOps[downloadId].promise = downloadOperation;
+
+ downloadOperation.then(function () {
+
+ // Update TransferOperation object with new state, delete promise property
+ // since it is not actual anymore
+ var currentDownloadOp = fileTransferOps[downloadId];
+ if (currentDownloadOp) {
+ currentDownloadOp.state = FileTransferOperation.DONE;
+ currentDownloadOp.promise = null;
+ }
+
+ var nativeURI = storageFile.path.replace(appData.localFolder.path, 'ms-appdata:///local')
+ .replace(appData.temporaryFolder.path, 'ms-appdata:///temp')
+ .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
+ FileProxy.resolveLocalFileSystemURI(successCallback, null, [nativeURI]);
+ }, function(error) {
+
+ var getTransferError = new WinJS.Promise(function (resolve) {
+ // Handle download error here. If download was cancelled,
+ // message property will be specified
+ if (error.message === 'Canceled') {
+ resolve(new FTErr(FTErr.ABORT_ERR, source, target, null, null, error));
+ } else if (error && error.number === HTTP_E_STATUS_NOT_MODIFIED) {
+ resolve(new FTErr(FTErr.NOT_MODIFIED_ERR, source, target, 304, null, error));
+ } else {
+ // in the other way, try to get response property
+ var response = download.getResponseInformation();
+ if (!response) {
+ resolve(new FTErr(FTErr.CONNECTION_ERR, source, target));
+ } else {
+ var reader = new Windows.Storage.Streams.DataReader(download.getResultStreamAt(0));
+ reader.loadAsync(download.progress.bytesReceived).then(function (bytesLoaded) {
+ var payload = reader.readString(bytesLoaded);
+ resolve(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, response.statusCode, payload, error));
+ });
+ }
+ }
+ });
+ getTransferError.then(function (fileTransferError) {
+
+ // Update TransferOperation object with new state, delete promise property
+ // since it is not actual anymore
+ var currentDownloadOp = fileTransferOps[downloadId];
+ if (currentDownloadOp) {
+ currentDownloadOp.state = FileTransferOperation.CANCELLED;
+ currentDownloadOp.promise = null;
+ }
+
+ // Cleanup, remove incompleted file
+ storageFile.deleteAsync().then(function() {
+ errorCallback(fileTransferError);
+ });
+ });
+
+ }, function(evt) {
+
+ var progressEvent = new ProgressEvent('progress', {
+ loaded: evt.progress.bytesReceived,
+ total: evt.progress.totalBytesToReceive,
+ target: evt.resultFile
+ });
+ // when bytesReceived == 0, BackgroundDownloader has not yet differentiated whether it could get file length or not,
+ // when totalBytesToReceive == 0, BackgroundDownloader is unable to get file length
+ progressEvent.lengthComputable = (evt.progress.bytesReceived > 0) && (evt.progress.totalBytesToReceive > 0);
+
+ successCallback(progressEvent, { keepCallback: true });
+ });
+ }, function(error) {
+ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
+ });
+ };
+
+ var fileNotFoundErrorCallback = function(error) {
+ errorCallback(new FTErr(FTErr.FILE_NOT_FOUND_ERR, source, target, null, null, error));
+ };
+
+ Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(downloadCallback, function (error) {
+ // Handle non-existent directory
+ if (error.number === -2147024894) {
+ var parent = path.substr(0, path.lastIndexOf('\\')),
+ folderNameToCreate = path.substr(path.lastIndexOf('\\') + 1);
+
+ Windows.Storage.StorageFolder.getFolderFromPathAsync(parent).then(function(parentFolder) {
+ parentFolder.createFolderAsync(folderNameToCreate).then(downloadCallback, fileNotFoundErrorCallback);
+ }, fileNotFoundErrorCallback);
+ } else {
+ fileNotFoundErrorCallback();
+ }
+ });
+ },
+
+ abort: function (successCallback, error, options) {
+ var fileTransferOpId = options[0];
+
+ // Try to find transferOperation with id specified, and cancel its' promise
+ var currentOp = fileTransferOps[fileTransferOpId];
+ if (currentOp) {
+ currentOp.state = FileTransferOperation.CANCELLED;
+ currentOp.promise && currentOp.promise.cancel();
+ }
+ }
+
+};
+
+require("cordova/exec/proxy").add("FileTransfer",module.exports);
diff --git a/plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs b/plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs
new file mode 100644
index 0000000..4be46e8
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/src/wp/FileTransfer.cs
@@ -0,0 +1,994 @@
+/*
+ Licensed 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.
+*/
+
+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;
+using System.Reflection;
+
+namespace WPCordovaClassLib.Cordova.Commands
+{
+ public class FileTransfer : BaseCommand
+ {
+ public class DownloadRequestState
+ {
+ // This class stores the State of the request.
+ public HttpWebRequest request;
+ public TransferOptions options;
+ public bool isCancelled;
+
+ public DownloadRequestState()
+ {
+ request = null;
+ options = null;
+ isCancelled = false;
+ }
+ }
+
+ public class TransferOptions
+ {
+ /// File path to upload OR File path to download to
+ public string FilePath { get; set; }
+
+ public string Url { get; set; }
+ /// Flag to recognize if we should trust every host (only in debug environments)
+ public bool TrustAllHosts { get; set; }
+ public string Id { get; set; }
+ public string Headers { get; set; }
+ public string CallbackId { get; set; }
+ public bool ChunkedMode { get; set; }
+ /// Server address
+ public string Server { get; set; }
+ /// File key
+ public string FileKey { get; set; }
+ /// File name on the server
+ public string FileName { get; set; }
+ /// File Mime type
+ public string MimeType { get; set; }
+ /// Additional options
+ public string Params { get; set; }
+ public string Method { get; set; }
+
+ public TransferOptions()
+ {
+ FileKey = "file";
+ FileName = "image.jpg";
+ MimeType = "image/jpeg";
+ }
+ }
+
+ ///
+ /// Boundary symbol
+ ///
+ private string Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
+
+ // Error codes
+ public const int FileNotFoundError = 1;
+ public const int InvalidUrlError = 2;
+ public const int ConnectionError = 3;
+ public const int AbortError = 4; // not really an error, but whatevs
+
+ private static Dictionary InProcDownloads = new Dictionary();
+
+ // 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;
+
+
+
+ ///
+ /// Uploading response info
+ ///
+ [DataContract]
+ public class FileUploadResult
+ {
+ ///
+ /// Amount of sent bytes
+ ///
+ [DataMember(Name = "bytesSent")]
+ public long BytesSent { get; set; }
+
+ ///
+ /// Server response code
+ ///
+ [DataMember(Name = "responseCode")]
+ public long ResponseCode { get; set; }
+
+ ///
+ /// Server response
+ ///
+ [DataMember(Name = "response", EmitDefaultValue = false)]
+ public string Response { get; set; }
+
+ ///
+ /// Creates FileUploadResult object with response values
+ ///
+ /// Amount of sent bytes
+ /// Server response code
+ /// Server response
+ public FileUploadResult(long bytesSent, long responseCode, string response)
+ {
+ this.BytesSent = bytesSent;
+ this.ResponseCode = responseCode;
+ this.Response = response;
+ }
+ }
+ ///
+ /// Represents transfer error codes for callback
+ ///
+ [DataContract]
+ public class FileTransferError
+ {
+ ///
+ /// Error code
+ ///
+ [DataMember(Name = "code", IsRequired = true)]
+ public int Code { get; set; }
+
+ ///
+ /// The source URI
+ ///
+ [DataMember(Name = "source", IsRequired = true)]
+ public string Source { get; set; }
+
+ ///
+ /// The target URI
+ ///
+ ///
+ [DataMember(Name = "target", IsRequired = true)]
+ public string Target { get; set; }
+
+ [DataMember(Name = "body", IsRequired = true)]
+ public string Body { get; set; }
+
+ ///
+ /// The http status code response from the remote URI
+ ///
+ [DataMember(Name = "http_status", IsRequired = true)]
+ public int HttpStatus { get; set; }
+
+ ///
+ /// Creates FileTransferError object
+ ///
+ /// Error code
+ public FileTransferError(int errorCode)
+ {
+ this.Code = errorCode;
+ this.Source = null;
+ this.Target = null;
+ this.HttpStatus = 0;
+ this.Body = "";
+ }
+ public FileTransferError(int errorCode, string source, string target, int status, string body = "")
+ {
+ this.Code = errorCode;
+ this.Source = source;
+ this.Target = target;
+ this.HttpStatus = status;
+ this.Body = body;
+ }
+ }
+
+ ///
+ /// Represents a singular progress event to be passed back to javascript
+ ///
+ [DataContract]
+ public class FileTransferProgress
+ {
+ ///
+ /// Is the length of the response known?
+ ///
+ [DataMember(Name = "lengthComputable", IsRequired = true)]
+ public bool LengthComputable { get; set; }
+ ///
+ /// amount of bytes loaded
+ ///
+ [DataMember(Name = "loaded", IsRequired = true)]
+ public long BytesLoaded { get; set; }
+ ///
+ /// Total bytes
+ ///
+ [DataMember(Name = "total", IsRequired = false)]
+ public long BytesTotal { get; set; }
+
+ public FileTransferProgress(long bTotal = 0, long bLoaded = 0)
+ {
+ LengthComputable = bTotal > 0;
+ BytesLoaded = bLoaded;
+ BytesTotal = bTotal;
+ }
+ }
+
+ ///
+ /// Represents a request header passed from Javascript to upload/download operations
+ ///
+ [DataContract]
+ protected struct Header
+ {
+ [DataMember(Name = "name")]
+ public string Name;
+
+ [DataMember(Name = "value")]
+ public string Value;
+ }
+
+ private static MethodInfo JsonDeserializeUsingJsonNet;
+
+ public FileTransfer()
+ {
+ if (JsonDeserializeUsingJsonNet == null)
+ {
+ var method = typeof(JsonHelper).GetMethod("Deserialize", new Type[] { typeof(string), typeof(bool) });
+ if (method != null)
+ {
+ JsonDeserializeUsingJsonNet = method.MakeGenericMethod(new Type[] { typeof(Header[]) });
+ }
+ }
+ }
+
+ /// Helper method to copy all relevant cookies from the WebBrowser control into a header on
+ /// the HttpWebRequest
+ ///
+ /// The source browser to copy the cookies from
+ /// The destination HttpWebRequest to add the cookie header to
+ /// Nothing
+ private async Task CopyCookiesFromWebBrowser(HttpWebRequest webRequest)
+ {
+ var tcs = new TaskCompletionSource();
+
+ // 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;
+ }
+
+ ///
+ /// Upload options
+ ///
+ //private TransferOptions uploadOptions;
+
+ ///
+ /// Bytes sent
+ ///
+ private long bytesSent;
+
+ ///
+ /// sends a file to a server
+ ///
+ /// Upload options
+ /// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+ public void upload(string options)
+ {
+ options = options.Replace("{}", ""); // empty objects screw up the Deserializer
+ string callbackId = "";
+
+ TransferOptions uploadOptions = null;
+ HttpWebRequest webRequest = null;
+
+ try
+ {
+ try
+ {
+ string[] args = JSON.JsonHelper.Deserialize(options);
+ uploadOptions = new TransferOptions();
+ uploadOptions.FilePath = args[0];
+ uploadOptions.Server = args[1];
+ uploadOptions.FileKey = args[2];
+ uploadOptions.FileName = args[3];
+ uploadOptions.MimeType = args[4];
+ uploadOptions.Params = args[5];
+
+ bool trustAll = false;
+ bool.TryParse(args[6],out trustAll);
+ uploadOptions.TrustAllHosts = trustAll;
+
+ bool doChunked = false;
+ bool.TryParse(args[7], out doChunked);
+ uploadOptions.ChunkedMode = doChunked;
+
+ //8 : Headers
+ //9 : id
+ //10: method
+
+ uploadOptions.Headers = args[8];
+ uploadOptions.Id = args[9];
+ uploadOptions.Method = args[10];
+
+ uploadOptions.CallbackId = callbackId = args[11];
+ }
+ catch (Exception)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ return;
+ }
+
+ Uri serverUri;
+ try
+ {
+ serverUri = new Uri(uploadOptions.Server);
+ }
+ catch (Exception)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
+ return;
+ }
+ webRequest = (HttpWebRequest)WebRequest.Create(serverUri);
+ webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
+ webRequest.Method = uploadOptions.Method;
+
+ DownloadRequestState reqState = new DownloadRequestState();
+ InProcDownloads[uploadOptions.Id] = reqState;
+ reqState.options = uploadOptions;
+ reqState.request = webRequest;
+
+ 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 headers = parseHeaders(uploadOptions.Headers);
+ if (headers != null)
+ {
+ foreach (string key in headers.Keys)
+ {
+ webRequest.Headers[key] = headers[key];
+ }
+ }
+ }
+
+ webRequest.BeginGetRequestStream(uploadCallback, reqState);
+ }
+ catch (Exception /*ex*/)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId);
+ }
+ }
+
+ // example : "{\"Authorization\":\"Basic Y29yZG92YV91c2VyOmNvcmRvdmFfcGFzc3dvcmQ=\"}"
+ protected Dictionary parseHeaders(string jsonHeaders)
+ {
+ try
+ {
+ if (FileTransfer.JsonDeserializeUsingJsonNet != null)
+ {
+ return ((Header[])FileTransfer.JsonDeserializeUsingJsonNet.Invoke(null, new object[] { jsonHeaders, true }))
+ .ToDictionary(header => header.Name, header => header.Value);
+ }
+ else
+ {
+ return JsonHelper.Deserialize(jsonHeaders)
+ .ToDictionary(header => header.Name, header => header.Value);
+ }
+ }
+ catch (Exception)
+ {
+ Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders);
+ }
+ return new Dictionary();
+ }
+
+ public void download(string options)
+ {
+ TransferOptions downloadOptions = null;
+ HttpWebRequest webRequest = null;
+ string callbackId;
+
+ try
+ {
+ // source, target, trustAllHosts, this._id, headers
+ string[] optionStrings = JSON.JsonHelper.Deserialize(options);
+
+ downloadOptions = new TransferOptions();
+ downloadOptions.Url = optionStrings[0];
+ downloadOptions.FilePath = optionStrings[1];
+
+ bool trustAll = false;
+ bool.TryParse(optionStrings[2],out trustAll);
+ downloadOptions.TrustAllHosts = trustAll;
+
+ downloadOptions.Id = optionStrings[3];
+ downloadOptions.Headers = optionStrings[4];
+ downloadOptions.CallbackId = callbackId = optionStrings[5];
+ }
+ catch (Exception)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ return;
+ }
+
+ try
+ {
+ // is the URL a local app file?
+ if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
+ {
+ using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
+ {
+ string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");
+
+ // pre-emptively create any directories in the FilePath that do not exist
+ string directoryName = getDirectoryName(downloadOptions.FilePath);
+ if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
+ {
+ isoFile.CreateDirectory(directoryName);
+ }
+
+ // just copy from one area of iso-store to another ...
+ if (isoFile.FileExists(downloadOptions.Url))
+ {
+ isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
+ }
+ else
+ {
+ // need to unpack resource from the dll
+ Uri uri = new Uri(cleanUrl, UriKind.Relative);
+ var resource = Application.GetResourceStream(uri);
+
+ if (resource != null)
+ {
+ // create the file destination
+ if (!isoFile.FileExists(downloadOptions.FilePath))
+ {
+ var destFile = isoFile.CreateFile(downloadOptions.FilePath);
+ destFile.Close();
+ }
+
+ using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
+ {
+ long totalBytes = resource.Stream.Length;
+ int bytesRead = 0;
+ using (BinaryReader reader = new BinaryReader(resource.Stream))
+ {
+ using (BinaryWriter writer = new BinaryWriter(fileStream))
+ {
+ int BUFFER_SIZE = 1024;
+ byte[] buffer;
+
+ while (true)
+ {
+ buffer = reader.ReadBytes(BUFFER_SIZE);
+ // fire a progress event ?
+ bytesRead += buffer.Length;
+ if (buffer.Length > 0)
+ {
+ writer.Write(buffer);
+ DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
+ }
+ else
+ {
+ writer.Close();
+ reader.Close();
+ fileStream.Close();
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
+ if (entry != null)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
+ }
+ else
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
+ }
+
+ return;
+ }
+ else
+ {
+ // otherwise it is web-bound, we will actually download it
+ //Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
+ webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
+ }
+ }
+ catch (Exception /*ex*/)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
+ return;
+ }
+
+ if (downloadOptions != null && webRequest != null)
+ {
+ DownloadRequestState state = new DownloadRequestState();
+ state.options = downloadOptions;
+ 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 headers = parseHeaders(downloadOptions.Headers);
+ foreach (string key in headers.Keys)
+ {
+ webRequest.Headers[key] = headers[key];
+ }
+ }
+
+ try
+ {
+ webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
+ }
+ catch (WebException)
+ {
+ // eat it
+ }
+ // dispatch an event for progress ( 0 )
+ lock (state)
+ {
+ if (!state.isCancelled)
+ {
+ var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
+ plugRes.KeepCallback = true;
+ plugRes.CallbackId = callbackId;
+ DispatchCommandResult(plugRes, callbackId);
+ }
+ }
+ }
+ }
+
+ public void abort(string options)
+ {
+ Debug.WriteLine("Abort :: " + options);
+ string[] optionStrings = JSON.JsonHelper.Deserialize(options);
+ string id = optionStrings[0];
+ string callbackId = optionStrings[1];
+
+ if (id != null && InProcDownloads.ContainsKey(id))
+ {
+ DownloadRequestState state = InProcDownloads[id];
+ if (!state.isCancelled)
+ { // prevent multiple callbacks for the same abort
+ state.isCancelled = true;
+ if (!state.request.HaveResponse)
+ {
+ state.request.Abort();
+ InProcDownloads.Remove(id);
+ //callbackId = state.options.CallbackId;
+ //state = null;
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(FileTransfer.AbortError)),
+ state.options.CallbackId);
+ }
+ }
+ }
+ else
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception?
+ }
+ }
+
+ private void DispatchFileTransferProgress(long bytesLoaded, long bytesTotal, string callbackId, bool keepCallback = true)
+ {
+ Debug.WriteLine("DispatchFileTransferProgress : " + callbackId);
+ // send a progress change event
+ FileTransferProgress progEvent = new FileTransferProgress(bytesTotal);
+ progEvent.BytesLoaded = bytesLoaded;
+ PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvent);
+ plugRes.KeepCallback = keepCallback;
+ plugRes.CallbackId = callbackId;
+ DispatchCommandResult(plugRes, callbackId);
+ }
+
+ ///
+ ///
+ ///
+ ///
+ private void downloadCallback(IAsyncResult asynchronousResult)
+ {
+ DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
+ HttpWebRequest request = reqState.request;
+
+ string callbackId = reqState.options.CallbackId;
+ try
+ {
+ HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
+
+ // send a progress change event
+ DispatchFileTransferProgress(0, response.ContentLength, callbackId);
+
+ using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
+ {
+ // create any directories in the path that do not exist
+ string directoryName = getDirectoryName(reqState.options.FilePath);
+ if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
+ {
+ isoFile.CreateDirectory(directoryName);
+ }
+
+ // create the file if not exists
+ if (!isoFile.FileExists(reqState.options.FilePath))
+ {
+ var file = isoFile.CreateFile(reqState.options.FilePath);
+ file.Close();
+ }
+
+ using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
+ {
+ long totalBytes = response.ContentLength;
+ int bytesRead = 0;
+ using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
+ {
+ using (BinaryWriter writer = new BinaryWriter(fileStream))
+ {
+ int BUFFER_SIZE = 1024;
+ byte[] buffer;
+
+ while (true)
+ {
+ buffer = reader.ReadBytes(BUFFER_SIZE);
+ // fire a progress event ?
+ bytesRead += buffer.Length;
+ if (buffer.Length > 0 && !reqState.isCancelled)
+ {
+ writer.Write(buffer);
+ DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
+ }
+ else
+ {
+ writer.Close();
+ reader.Close();
+ fileStream.Close();
+ break;
+ }
+ System.Threading.Thread.Sleep(1);
+ }
+ }
+ }
+ }
+ if (reqState.isCancelled)
+ {
+ isoFile.DeleteFile(reqState.options.FilePath);
+ }
+ }
+
+ if (reqState.isCancelled)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)),
+ callbackId);
+ }
+ else
+ {
+ File.FileEntry entry = new File.FileEntry(reqState.options.FilePath);
+ DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
+ }
+ }
+ catch (IsolatedStorageException)
+ {
+ // Trying to write the file somewhere within the IsoStorage.
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
+ callbackId);
+ }
+ catch (SecurityException)
+ {
+ // Trying to write the file somewhere not allowed.
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
+ callbackId);
+ }
+ catch (WebException webex)
+ {
+ // TODO: probably need better work here to properly respond with all http status codes back to JS
+ // Right now am jumping through hoops just to detect 404.
+ HttpWebResponse response = (HttpWebResponse)webex.Response;
+ if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound)
+ || webex.Status == WebExceptionStatus.UnknownError)
+ {
+ // Weird MSFT detection of 404... seriously... just give us the f(*$@ status code as a number ffs!!!
+ // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
+ // FACEPALM
+ // Or just cast it to an int, whiner ... -jm
+ int statusCode = (int)response.StatusCode;
+ string body = "";
+
+ using (Stream streamResponse = response.GetResponseStream())
+ {
+ using (StreamReader streamReader = new StreamReader(streamResponse))
+ {
+ body = streamReader.ReadToEnd();
+ }
+ }
+ FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body);
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError),
+ callbackId);
+ }
+ else
+ {
+ lock (reqState)
+ {
+ if (!reqState.isCancelled)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(ConnectionError)),
+ callbackId);
+ }
+ else
+ {
+ Debug.WriteLine("It happened");
+ }
+ }
+ }
+ }
+ catch (Exception)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(FileNotFoundError)),
+ callbackId);
+ }
+
+ //System.Threading.Thread.Sleep(1000);
+ if (InProcDownloads.ContainsKey(reqState.options.Id))
+ {
+ InProcDownloads.Remove(reqState.options.Id);
+ }
+ }
+
+ ///
+ /// Read file from Isolated Storage and sends it to server
+ ///
+ ///
+ private void uploadCallback(IAsyncResult asynchronousResult)
+ {
+ DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
+ HttpWebRequest webRequest = reqState.request;
+ string callbackId = reqState.options.CallbackId;
+
+ try
+ {
+ using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
+ {
+ string lineStart = "--";
+ string lineEnd = Environment.NewLine;
+ byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
+ string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;
+
+ if (!string.IsNullOrEmpty(reqState.options.Params))
+ {
+ Dictionary paramMap = parseHeaders(reqState.options.Params);
+ foreach (string key in paramMap.Keys)
+ {
+ requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
+ string formItem = string.Format(formdataTemplate, key, paramMap[key]);
+ byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
+ requestStream.Write(formItemBytes, 0, formItemBytes.Length);
+ }
+ }
+ using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
+ {
+ if (!isoFile.FileExists(reqState.options.FilePath))
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0)));
+ return;
+ }
+
+ byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
+ long totalBytesToSend = 0;
+
+ using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile))
+ {
+ string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
+ string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType);
+ byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
+
+ byte[] buffer = new byte[4096];
+ int bytesRead = 0;
+ //sent bytes needs to be reseted before new upload
+ bytesSent = 0;
+ totalBytesToSend = fileStream.Length;
+
+ requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
+
+ requestStream.Write(headerBytes, 0, headerBytes.Length);
+
+ while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
+ {
+ if (!reqState.isCancelled)
+ {
+ requestStream.Write(buffer, 0, bytesRead);
+ bytesSent += bytesRead;
+ DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId);
+ System.Threading.Thread.Sleep(1);
+ }
+ else
+ {
+ throw new Exception("UploadCancelledException");
+ }
+ }
+ }
+
+ requestStream.Write(endRequest, 0, endRequest.Length);
+ }
+ }
+ // webRequest
+
+ webRequest.BeginGetResponse(ReadCallback, reqState);
+ }
+ catch (Exception /*ex*/)
+ {
+ if (!reqState.isCancelled)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
+ }
+ }
+ }
+
+ ///
+ /// Reads response into FileUploadResult
+ ///
+ ///
+ private void ReadCallback(IAsyncResult asynchronousResult)
+ {
+ DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
+ try
+ {
+ HttpWebRequest webRequest = reqState.request;
+ string callbackId = reqState.options.CallbackId;
+
+ if (InProcDownloads.ContainsKey(reqState.options.Id))
+ {
+ InProcDownloads.Remove(reqState.options.Id);
+ }
+
+ using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
+ {
+ using (Stream streamResponse = response.GetResponseStream())
+ {
+ using (StreamReader streamReader = new StreamReader(streamResponse))
+ {
+ string responseString = streamReader.ReadToEnd();
+ Deployment.Current.Dispatcher.BeginInvoke(() =>
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString)));
+ });
+ }
+ }
+ }
+ }
+ catch (WebException webex)
+ {
+ // TODO: probably need better work here to properly respond with all http status codes back to JS
+ // Right now am jumping through hoops just to detect 404.
+ if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound)
+ || webex.Status == WebExceptionStatus.UnknownError)
+ {
+ int statusCode = (int)((HttpWebResponse)webex.Response).StatusCode;
+ FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode);
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId);
+ }
+ else
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ new FileTransferError(ConnectionError)),
+ reqState.options.CallbackId);
+ }
+ }
+ catch (Exception /*ex*/)
+ {
+ FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403);
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId);
+ }
+ }
+
+ // Gets the full path without the filename
+ private string getDirectoryName(String filePath)
+ {
+ string directoryName;
+ try
+ {
+ directoryName = filePath.Substring(0, filePath.LastIndexOf('/'));
+ }
+ catch
+ {
+ directoryName = "";
+ }
+ return directoryName;
+ }
+ }
+}
diff --git a/plugins/cordova-plugin-file-transfer/tests/plugin.xml b/plugins/cordova-plugin-file-transfer/tests/plugin.xml
new file mode 100644
index 0000000..eabf271
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/tests/plugin.xml
@@ -0,0 +1,30 @@
+
+
+
+
+ Cordova File Transfer Plugin Tests
+ Apache 2.0
+
+
+
+
diff --git a/plugins/cordova-plugin-file-transfer/tests/tests.js b/plugins/cordova-plugin-file-transfer/tests/tests.js
new file mode 100644
index 0000000..fff1eef
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/tests/tests.js
@@ -0,0 +1,1045 @@
+/*
+*
+* 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.
+*
+*/
+
+/*global exports, cordova, FileTransfer, FileTransferError,
+ FileUploadOptions, LocalFileSystem, requestFileSystem, TEMPORARY */
+
+/*global describe, it, expect, beforeEach, afterEach, spyOn,
+ jasmine, pending*/
+
+exports.defineAutoTests = function () {
+
+ // constants
+ 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 = 30 * 1000; // download tests sometimes need a higher timeout to complete successfully
+ var UPLOAD_TIMEOUT = 30 * 1000; // upload tests sometimes need a higher timeout to complete successfully
+ var ABORT_DELAY = 100; // for abort() tests
+
+ // config for upload test server
+ // NOTE:
+ // more info at https://github.com/apache/cordova-labs/tree/cordova-filetransfer
+ var SERVER = "http://cordova-vm.apache.org:5000";
+ var SERVER_WITH_CREDENTIALS = "http://cordova_user:cordova_password@cordova-vm.apache.org:5000";
+
+ // flags
+ var isWindows = cordova.platformId === 'windows8' || cordova.platformId === 'windows';
+ var isWP8 = cordova.platformId === 'windowsphone';
+ var isBrowser = cordova.platformId === 'browser';
+ var isIE = isBrowser && navigator.userAgent.indexOf('Trident') >= 0;
+
+ describe('FileTransferError', function () {
+
+ it('should exist', function () {
+ expect(FileTransferError).toBeDefined();
+ });
+
+ it('should be constructable', function () {
+ var transferError = new FileTransferError();
+ expect(transferError).toBeDefined();
+ });
+
+ it('filetransfer.spec.3 should expose proper constants', function () {
+
+ expect(FileTransferError.FILE_NOT_FOUND_ERR).toBeDefined();
+ expect(FileTransferError.INVALID_URL_ERR).toBeDefined();
+ expect(FileTransferError.CONNECTION_ERR).toBeDefined();
+ expect(FileTransferError.ABORT_ERR).toBeDefined();
+ expect(FileTransferError.NOT_MODIFIED_ERR).toBeDefined();
+
+ expect(FileTransferError.FILE_NOT_FOUND_ERR).toBe(1);
+ expect(FileTransferError.INVALID_URL_ERR).toBe(2);
+ expect(FileTransferError.CONNECTION_ERR).toBe(3);
+ expect(FileTransferError.ABORT_ERR).toBe(4);
+ expect(FileTransferError.NOT_MODIFIED_ERR).toBe(5);
+ });
+ });
+
+ describe('FileUploadOptions', function () {
+
+ it('should exist', function () {
+ expect(FileUploadOptions).toBeDefined();
+ });
+
+ it('should be constructable', function () {
+ var transferOptions = new FileUploadOptions();
+ expect(transferOptions).toBeDefined();
+ });
+ });
+
+ describe('FileTransfer', function () {
+
+ var persistentRoot, tempRoot;
+
+ // named callbacks
+ var unexpectedCallbacks = {
+ httpFail: function () {},
+ httpWin: function () {},
+ fileSystemFail: function () {},
+ fileSystemWin: function () {},
+ fileOperationFail: function () {},
+ fileOperationWin: function () {},
+ };
+
+ var expectedCallbacks = {
+ unsupportedOperation: function (response) {
+ console.log('spec called unsupported functionality; response:', response);
+ },
+ };
+
+ // helpers
+ var deleteFile = function (fileSystem, name, done) {
+ fileSystem.getFile(name, null,
+ function (fileEntry) {
+ fileEntry.remove(
+ function () {
+ done();
+ },
+ function () {
+ throw new Error('failed to delete: \'' + name + '\'');
+ }
+ );
+ },
+ function () {
+ done();
+ }
+ );
+ };
+
+ var writeFile = function (fileSystem, name, content, success) {
+ fileSystem.getFile(name, { create: true },
+ function (fileEntry) {
+ fileEntry.createWriter(function (writer) {
+
+ writer.onwrite = function () {
+ success(fileEntry);
+ };
+
+ writer.onabort = function (evt) {
+ throw new Error('aborted creating test file \'' + name + '\': ' + evt);
+ };
+
+ writer.error = function (evt) {
+ throw new Error('aborted creating test file \'' + name + '\': ' + evt);
+ };
+
+ if (cordova.platformId === 'browser') {
+ // var builder = new BlobBuilder();
+ // builder.append(content + '\n');
+ var blob = new Blob([content + '\n'], { type: 'text/plain' });
+ writer.write(blob);
+ } else {
+ writer.write(content + "\n");
+ }
+
+ }, unexpectedCallbacks.fileOperationFail);
+ },
+ function () {
+ throw new Error('could not create test file \'' + name + '\'');
+ }
+ );
+ };
+
+ // according to documentation, wp8 does not support onProgress:
+ // https://github.com/apache/cordova-plugin-file-transfer/blob/master/doc/index.md#supported-platforms
+ var wp8OnProgressHandler = function () {};
+
+ var defaultOnProgressHandler = function (event) {
+ if (event.lengthComputable) {
+ expect(event.loaded).toBeGreaterThan(1);
+ expect(event.total).toBeGreaterThan(0);
+ expect(event.total).not.toBeLessThan(event.loaded);
+ expect(event.lengthComputable).toBe(true, 'lengthComputable');
+ } else {
+ // In IE, when lengthComputable === false, event.total somehow is equal to 2^64
+ if (isIE) {
+ expect(event.total).toBe(Math.pow(2, 64));
+ } else {
+ // iOS returns -1, and other platforms return 0
+ expect(event.total).toBeLessThan(1);
+ }
+ }
+ };
+
+ var getMalformedUrl = function () {
+ if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos') {
+ // bad protocol causes a MalformedUrlException on Android
+ return "httpssss://example.com";
+ } else {
+ // iOS doesn't care about protocol, space in hostname causes error
+ return "httpssss://exa mple.com";
+ }
+ };
+
+ // NOTE:
+ // there are several beforeEach calls, one per async call; since calling done()
+ // signifies a completed async call, each async call needs its own done(), and
+ // therefore its own beforeEach
+ beforeEach(function (done) {
+ window.requestFileSystem(LocalFileSystem.PERSISTENT, DEFAULT_FILESYSTEM_SIZE,
+ function (fileSystem) {
+ persistentRoot = fileSystem.root;
+ done();
+ },
+ function () {
+ throw new Error('Failed to initialize persistent file system.');
+ }
+ );
+ });
+
+ beforeEach(function (done) {
+ window.requestFileSystem(LocalFileSystem.TEMPORARY, DEFAULT_FILESYSTEM_SIZE,
+ function (fileSystem) {
+ tempRoot = fileSystem.root;
+ done();
+ },
+ function () {
+ throw new Error('Failed to initialize temporary file system.');
+ }
+ );
+ });
+
+ // spy on all named callbacks
+ beforeEach(function() {
+
+ // ignore the actual implementations of the unexpected callbacks
+ for (var callback in unexpectedCallbacks) {
+ if (unexpectedCallbacks.hasOwnProperty(callback)) {
+ spyOn(unexpectedCallbacks, callback);
+ }
+ }
+
+ // but run the implementations of the expected callbacks
+ for (callback in expectedCallbacks) { //jshint ignore: line
+ if (expectedCallbacks.hasOwnProperty(callback)) {
+ spyOn(expectedCallbacks, callback).and.callThrough();
+ }
+ }
+ });
+
+ // at the end, check that none of the unexpected callbacks got called,
+ // and act on the expected callbacks
+ afterEach(function() {
+ for (var callback in unexpectedCallbacks) {
+ if (unexpectedCallbacks.hasOwnProperty(callback)) {
+ expect(unexpectedCallbacks[callback]).not.toHaveBeenCalled();
+ }
+ }
+
+ if (expectedCallbacks.unsupportedOperation.calls.any()) {
+ pending();
+ }
+ });
+
+ it('should initialise correctly', function() {
+ expect(persistentRoot).toBeDefined();
+ expect(tempRoot).toBeDefined();
+ });
+
+ it('should exist', function () {
+ expect(FileTransfer).toBeDefined();
+ });
+
+ it('filetransfer.spec.1 should be constructable', function () {
+ var transfer = new FileTransfer();
+ expect(transfer).toBeDefined();
+ });
+
+ it('filetransfer.spec.2 should expose proper functions', function () {
+
+ var transfer = new FileTransfer();
+
+ expect(transfer.upload).toBeDefined();
+ expect(transfer.download).toBeDefined();
+
+ expect(transfer.upload).toEqual(jasmine.any(Function));
+ expect(transfer.download).toEqual(jasmine.any(Function));
+ });
+
+ describe('methods', function() {
+
+ var transfer;
+
+ var root;
+ var fileName;
+ var localFilePath;
+
+ beforeEach(function() {
+
+ transfer = new FileTransfer();
+
+ // assign onprogress handler
+ transfer.onprogress = isWP8 ? wp8OnProgressHandler : defaultOnProgressHandler;
+
+ // spy on the onprogress handler, but still call through to it
+ spyOn(transfer, 'onprogress').and.callThrough();
+
+ root = persistentRoot;
+ fileName = 'testFile.txt';
+ localFilePath = root.toURL() + fileName;
+ });
+
+ // NOTE:
+ // if download tests are failing, check the
+ // URL white list for the following URLs:
+ // - 'httpssss://example.com'
+ // - 'apache.org', with subdomains="true"
+ // - 'cordova-filetransfer.jitsu.com'
+ describe('download', function () {
+
+ // helpers
+ var verifyDownload = function (fileEntry) {
+ expect(fileEntry.name).toBe(fileName);
+ };
+
+ // delete the downloaded file
+ afterEach(function (done) {
+ 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';
+
+ var fileWin = function (blob) {
+
+ if (transfer.onprogress.calls.any()) {
+ var lastProgressEvent = transfer.onprogress.calls.mostRecent().args[0];
+ expect(lastProgressEvent.loaded).not.toBeGreaterThan(blob.size);
+ } else {
+ console.log('no progress events were emitted');
+ }
+
+ done();
+ };
+
+ var downloadWin = function (entry) {
+
+ verifyDownload(entry);
+
+ // verify the FileEntry representing this file
+ entry.file(fileWin, unexpectedCallbacks.fileSystemFail);
+ };
+
+ transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
+ }, DOWNLOAD_TIMEOUT);
+
+ it('filetransfer.spec.5 should download a file using http basic auth', function (done) {
+
+ var fileURL = SERVER_WITH_CREDENTIALS + '/download_basic_auth';
+
+ var downloadWin = function (entry) {
+ verifyDownload(entry);
+ done();
+ };
+
+ transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
+ }, DOWNLOAD_TIMEOUT);
+
+ it('filetransfer.spec.6 should get 401 status on http basic auth failure', function (done) {
+
+ // NOTE:
+ // using server without credentials
+ var fileURL = SERVER + '/download_basic_auth';
+
+ var downloadFail = function (error) {
+ expect(error.http_status).toBe(401);
+ expect(error.http_status).not.toBe(404, "Ensure " + fileURL + " is in the white list");
+ done();
+ };
+
+ 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) {
+
+ // for Windows platform it's ms-appdata:/// by default, not file://
+ if (isWindows) {
+ pending();
+ return;
+ }
+
+ var fileURL = window.location.protocol + '//' + window.location.pathname.replace(/ /g, '%20');
+
+ if (!/^file:/.exec(fileURL) && cordova.platformId !== 'blackberry10') {
+ if (cordova.platformId === 'windowsphone')
+ expect(fileURL).toMatch(/^x-wmapp0:/);
+ done();
+ return;
+ }
+
+ var downloadWin = function (entry) {
+ verifyDownload(entry);
+ done();
+ };
+
+ transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
+ }, DOWNLOAD_TIMEOUT);
+
+ it("filetransfer.spec.8 should download a file using https://", function (done) {
+
+ var fileURL = "https://www.apache.org/licenses/";
+
+ var fileWin = function (file) {
+
+ var reader = new FileReader();
+
+ reader.onerror = unexpectedCallbacks.fileOperationFail;
+ reader.onload = function () {
+ expect(reader.result).toMatch(/The Apache Software Foundation/);
+ done();
+ };
+
+ reader.readAsText(file);
+ };
+
+ var downloadWin = function (entry) {
+ verifyDownload(entry);
+ entry.file(fileWin, unexpectedCallbacks.fileSystemFail);
+ };
+
+ 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);
+ setTimeout(function() {
+ transfer.abort();
+ }, ABORT_DELAY);
+ }, DOWNLOAD_TIMEOUT);
+
+ it("filetransfer.spec.9 should not leave partial file due to abort", function (done) {
+
+ var fileURL = 'http://cordova.apache.org/downloads/logos_2.zip';
+
+ var downloadFail = function (error) {
+
+ expect(error.code).toBe(FileTransferError.ABORT_ERR);
+ expect(transfer.onprogress).toHaveBeenCalled();
+
+ // check that there is no file
+ root.getFile(localFilePath, null, unexpectedCallbacks.fileSystemWin, done);
+ };
+
+ // abort at the first onprogress event
+ transfer.onprogress = function (event) {
+ if (event.loaded > 0) {
+ transfer.abort();
+ }
+ };
+
+ 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) {
+
+ var fileURL = 'http://cordova.apache.org/downloads/BlueZedEx.mp3';
+
+ expect(transfer.abort).not.toThrow(); // should be a no-op.
+
+ var startTime = +new Date();
+
+ var downloadFail = function (error) {
+
+ expect(error.code).toBe(FileTransferError.ABORT_ERR);
+ expect(new Date() - startTime).toBeLessThan(GRACE_TIME_DELTA);
+
+ // delay calling done() to wait for the bogus abort()
+ setTimeout(done, GRACE_TIME_DELTA * 2);
+ };
+
+ transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
+ 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) {
+
+ var fileURL = SERVER + "/404";
+
+ var downloadFail = function (error) {
+
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ expect(error.http_status).toBe(404);
+
+ // wp8 does not make difference between 404 and unknown host
+ if (isWP8) {
+ expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
+ } else {
+ expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR);
+ }
+
+ done();
+ };
+
+ transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
+ }, DOWNLOAD_TIMEOUT);
+
+ it("filetransfer.spec.13 should get http body on failure", function (done) {
+
+ var fileURL = SERVER + "/404";
+
+ var downloadFail = function (error) {
+
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ expect(error.http_status).toBe(404);
+
+ expect(error.body).toBeDefined();
+ expect(error.body).toMatch('You requested a 404');
+
+ done();
+ };
+
+ transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
+ }, DOWNLOAD_TIMEOUT);
+
+ it("filetransfer.spec.14 should handle malformed urls", function (done) {
+
+ var fileURL = getMalformedUrl();
+
+ var downloadFail = function (error) {
+
+ // Note: Android needs the bad protocol to be added to the access list
+ // won't match because ^https?:// is prepended to the regex
+ // The bad protocol must begin with http to avoid automatic prefix
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ expect(error.code).toBe(FileTransferError.INVALID_URL_ERR);
+
+ done();
+ };
+
+ transfer.download(fileURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail);
+ });
+
+ 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);
+ }, DOWNLOAD_TIMEOUT);
+
+ it("filetransfer.spec.16 should handle bad file path", function (done) {
+ var fileURL = SERVER;
+ transfer.download(fileURL, "c:\\54321", unexpectedCallbacks.httpWin, done);
+ });
+
+ it("filetransfer.spec.17 progress should work with gzip encoding", function (done) {
+
+ // lengthComputable false on bb10 when downloading gzip
+ if (cordova.platformId === 'blackberry10') {
+ pending();
+ return;
+ }
+
+ var fileURL = "http://www.apache.org/";
+
+ var downloadWin = function (entry) {
+ verifyDownload(entry);
+ done();
+ };
+
+ transfer.download(fileURL, localFilePath, downloadWin, unexpectedCallbacks.httpFail);
+ }, DOWNLOAD_TIMEOUT);
+
+ it("filetransfer.spec.30 downloaded file entries should have a toNativeURL method", function (done) {
+
+ if (cordova.platformId === 'browser') {
+ pending();
+ return;
+ }
+
+ var fileURL = SERVER + "/robots.txt";
+
+ var downloadWin = function (entry) {
+
+ expect(entry.toNativeURL).toBeDefined();
+ expect(entry.toNativeURL).toEqual(jasmine.any(Function));
+
+ var nativeURL = entry.toNativeURL();
+
+ expect(nativeURL).toBeTruthy();
+ expect(nativeURL).toEqual(jasmine.any(String));
+
+ if (isWindows) {
+ expect(nativeURL.substring(0, 14)).toBe('ms-appdata:///');
+ } else if (isWP8) {
+ expect(nativeURL.substring(0, 1)).toBe('/');
+ } else {
+ expect(nativeURL.substring(0, 7)).toBe('file://');
+ }
+
+ done();
+ };
+
+ 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) {
+
+ var fileURL = SERVER + "/robots.txt";
+
+ var unsupported = function (response) {
+ expectedCallbacks.unsupportedOperation(response);
+ done();
+ };
+
+ var downloadWin = function (entry) {
+ verifyDownload(entry);
+ done();
+ };
+
+ var internalFilePath;
+ if (root.toInternalURL) {
+ internalFilePath = root.toInternalURL() + fileName;
+ } else {
+ internalFilePath = localFilePath;
+ }
+
+ // This is an undocumented interface to File which exists only for testing
+ // backwards compatibilty. By obtaining the raw filesystem path of the download
+ // location, we can pass that to transfer.download() to make sure that previously-stored
+ // paths are still valid.
+ cordova.exec(function (localPath) {
+ transfer.download(fileURL, localPath, downloadWin, unexpectedCallbacks.httpFail);
+ }, unsupported, 'File', '_getLocalFilesystemPath', [internalFilePath]);
+ });
+
+ it('filetransfer.spec.31 should properly handle 304', function (done) {
+
+ if(isWP8) {
+ pending();
+ return;
+ }
+
+ var imageURL = "http://apache.org/images/feather-small.gif";
+ var lastModified = new Date();
+
+ var downloadFail = function (error) {
+ expect(error.http_status).toBe(304);
+ expect(error.code).toBe(FileTransferError.NOT_MODIFIED_ERR);
+ done();
+ };
+
+ transfer.download(imageURL, localFilePath, unexpectedCallbacks.httpWin, downloadFail, null,
+ {
+ headers: {
+ 'If-Modified-Since': lastModified.toUTCString()
+ }
+ });
+ }, DOWNLOAD_TIMEOUT);
+ });
+
+ describe('upload', function() {
+
+ var uploadParams;
+ var uploadOptions;
+
+ var fileName;
+ var fileContents;
+ var localFilePath;
+
+ // helpers
+ var verifyUpload = function (uploadResult) {
+
+ expect(uploadResult.bytesSent).toBeGreaterThan(0);
+ expect(uploadResult.responseCode).toBe(200);
+
+ var obj = null;
+ try {
+ obj = JSON.parse(uploadResult.response);
+ expect(obj.fields).toBeDefined();
+ expect(obj.fields.value1).toBe("test");
+ expect(obj.fields.value2).toBe("param");
+ } catch (e) {
+ expect(obj).not.toBeNull('returned data from server should be valid json');
+ }
+
+ expect(transfer.onprogress).toHaveBeenCalled();
+ };
+
+ beforeEach(function(done) {
+
+ fileName = 'fileToUpload.txt';
+ fileContents = 'upload test file';
+
+ uploadParams = {};
+ uploadParams.value1 = "test";
+ uploadParams.value2 = "param";
+
+ uploadOptions = new FileUploadOptions();
+ uploadOptions.fileKey = "file";
+ uploadOptions.fileName = fileName;
+ uploadOptions.mimeType = "text/plain";
+ uploadOptions.params = uploadParams;
+
+ var fileWin = function (entry) {
+ localFilePath = entry.toURL();
+ done();
+ };
+
+ // create a file to upload
+ writeFile(root, fileName, fileContents, fileWin);
+ });
+
+ // delete the uploaded file
+ afterEach(function (done) {
+ deleteFile(root, fileName, done);
+ });
+
+ it("filetransfer.spec.18 should be able to upload a file", function (done) {
+
+ var fileURL = SERVER + '/upload';
+
+ var uploadWin = function (uploadResult) {
+
+ verifyUpload(uploadResult);
+
+ if (cordova.platformId === 'ios') {
+ expect(uploadResult.headers).toBeDefined('Expected headers to be defined.');
+ expect(uploadResult.headers['Content-Type']).toBeDefined('Expected content-type header to be defined.');
+ }
+
+ done();
+ };
+
+ // 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) {
+
+ var fileURL = SERVER_WITH_CREDENTIALS + "/upload_basic_auth";
+
+ var uploadWin = function (uploadResult) {
+ verifyUpload(uploadResult);
+ done();
+ };
+
+ // 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) {
+
+ var fileURL = SERVER + '/upload';
+ var startTime;
+
+ var uploadFail = function (e) {
+ expect(e.code).toBe(FileTransferError.ABORT_ERR);
+ expect(new Date() - startTime).toBeLessThan(GRACE_TIME_DELTA);
+
+ // delay calling done() to wait for the bogus abort()
+ setTimeout(done, GRACE_TIME_DELTA * 2);
+ };
+
+ var fileWin = function () {
+
+ startTime = +new Date();
+
+ expect(transfer.abort).not.toThrow();
+
+ // NOTE: removing uploadOptions cause Android to timeout
+ transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, uploadOptions);
+ setTimeout(function() {
+ transfer.abort();
+ }, ABORT_DELAY);
+
+ setTimeout(function () {
+ expect(transfer.abort).not.toThrow();
+ }, GRACE_TIME_DELTA);
+ };
+
+ 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) {
+
+ var fileURL = SERVER + '/403';
+
+ var uploadFail = function (error) {
+ expect(error.http_status).toBe(403);
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ done();
+ };
+
+ transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, uploadOptions);
+ }, UPLOAD_TIMEOUT);
+
+ it("filetransfer.spec.24 should handle malformed urls", function (done) {
+
+ var fileURL = getMalformedUrl();
+
+ var uploadFail = function (error) {
+ expect(error.code).toBe(FileTransferError.INVALID_URL_ERR);
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ done();
+ };
+
+ transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, {});
+ });
+
+ it("filetransfer.spec.25 should handle unknown host", function (done) {
+
+ var fileURL = UNKNOWN_HOST;
+
+ var uploadFail = function (error) {
+ expect(error.code).toBe(FileTransferError.CONNECTION_ERR);
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ done();
+ };
+
+ transfer.upload(localFilePath, fileURL, unexpectedCallbacks.httpWin, uploadFail, {});
+ }, UPLOAD_TIMEOUT);
+
+ it("filetransfer.spec.25 should handle missing file", function (done) {
+
+ var fileURL = SERVER + "/upload";
+
+ var uploadFail = function (error) {
+ expect(error.code).toBe(FileTransferError.FILE_NOT_FOUND_ERR);
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ done();
+ };
+
+ transfer.upload('does_not_exist.txt', fileURL, unexpectedCallbacks.httpWin, uploadFail);
+ }, UPLOAD_TIMEOUT);
+
+ it("filetransfer.spec.26 should handle bad file path", function (done) {
+
+ var fileURL = SERVER + "/upload";
+
+ var uploadFail = function (error) {
+ expect(error.http_status).not.toBe(401, "Ensure " + fileURL + " is in the white list");
+ done();
+ };
+
+ transfer.upload("c:\\54321", fileURL, unexpectedCallbacks.httpWin, uploadFail);
+ });
+
+ it("filetransfer.spec.27 should be able to set custom headers", function (done) {
+
+ var fileURL = HEADERS_ECHO;
+
+ var uploadWin = function (uploadResult) {
+
+ expect(uploadResult.bytesSent).toBeGreaterThan(0);
+ expect(uploadResult.responseCode).toBe(200);
+ expect(uploadResult.response).toBeDefined();
+
+ var responseHtml = decodeURIComponent(uploadResult.response);
+
+ expect(responseHtml).toMatch(/CustomHeader1[\s\S]*CustomValue1/i);
+ expect(responseHtml).toMatch(/CustomHeader2[\s\S]*CustomValue2[\s\S]*CustomValue3/i, "Should allow array values");
+
+ done();
+ };
+
+ uploadOptions.headers = {
+ "CustomHeader1": "CustomValue1",
+ "CustomHeader2": ["CustomValue2", "CustomValue3"],
+ };
+
+ // 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) {
+
+ var fileURL = SERVER + "/upload";
+
+ var unsupported = function (response) {
+ expectedCallbacks.unsupportedOperation(response);
+ done();
+ };
+
+ var uploadWin = function (uploadResult) {
+ verifyUpload(uploadResult);
+ done();
+ };
+
+ var internalFilePath;
+ if (root.toInternalURL) {
+ internalFilePath = root.toInternalURL() + fileName;
+ } else {
+ internalFilePath = localFilePath;
+ }
+
+ // This is an undocumented interface to File which exists only for testing
+ // backwards compatibilty. By obtaining the raw filesystem path of the download
+ // location, we can pass that to transfer.download() to make sure that previously-stored
+ // paths are still valid.
+ cordova.exec(function (localPath) {
+ transfer.upload(localPath, fileURL, uploadWin, unexpectedCallbacks.httpFail, uploadOptions);
+ }, unsupported, 'File', '_getLocalFilesystemPath', [internalFilePath]);
+ }, UPLOAD_TIMEOUT);
+
+ it("filetransfer.spec.31 should be able to upload a file using PUT method", function (done) {
+
+ var fileURL = SERVER + '/upload';
+
+ var uploadWin = function (uploadResult) {
+
+ verifyUpload(uploadResult);
+
+ if (cordova.platformId === 'ios') {
+ expect(uploadResult.headers).toBeDefined('Expected headers to be defined.');
+ expect(uploadResult.headers['Content-Type']).toBeDefined('Expected content-type header to be defined.');
+ }
+
+ done();
+ };
+
+ var uploadOptionsPut = new FileUploadOptions();
+ uploadOptionsPut.fileKey = "file";
+ uploadOptionsPut.fileName = fileName;
+ uploadOptionsPut.mimeType = "text/plain";
+ uploadOptionsPut.params = uploadParams;
+ uploadOptionsPut.httpMethod = "PUT";
+
+ // NOTE: removing uploadOptions cause Android to timeout
+ transfer.upload(localFilePath, fileURL, uploadWin, unexpectedCallbacks.httpFail, uploadOptionsPut);
+ }, UPLOAD_TIMEOUT);
+ });
+ });
+ });
+};
+
+/******************************************************************************/
+/******************************************************************************/
+/******************************************************************************/
+
+exports.defineManualTests = function (contentEl, createActionButton) {
+ var imageURL = "http://apache.org/images/feather-small.gif";
+ var videoURL = "http://techslides.com/demos/sample-videos/small.mp4";
+
+ function clearResults() {
+ var results = document.getElementById("info");
+ results.innerHTML = '';
+ }
+
+ function downloadImg(source, urlFn, element, directory) {
+ var filename = source.substring(source.lastIndexOf("/") + 1);
+ filename = (directory || '') + filename;
+ function download(fileSystem) {
+ var ft = new FileTransfer();
+ console.log("Starting download");
+ ft.download(source, fileSystem.root.toURL() + filename, function (entry) {
+ console.log("Download complete");
+ element.src = urlFn(entry);
+ console.log("Src URL is " + element.src);
+ console.log("Inserting element");
+ document.getElementById("info").appendChild(element);
+ }, function (e) { console.log("ERROR: ft.download " + e.code); });
+ }
+ console.log("Requesting filesystem");
+ clearResults();
+ window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) {
+ console.log("Checking for existing file");
+ if (typeof directory !== 'undefined') {
+ console.log("Checking for existing directory.");
+ fileSystem.root.getDirectory(directory, {}, function (dirEntry) {
+ dirEntry.removeRecursively(function () {
+ download(fileSystem);
+ }, function () { console.log("ERROR: dirEntry.removeRecursively"); });
+ }, function () {
+ download(fileSystem);
+ });
+ } else {
+ fileSystem.root.getFile(filename, { create: false }, function (entry) {
+ console.log("Removing existing file");
+ entry.remove(function () {
+ download(fileSystem);
+ }, function () { console.log("ERROR: entry.remove"); });
+ }, function () {
+ download(fileSystem);
+ });
+ }
+ }, function () { console.log("ERROR: requestFileSystem"); });
+ }
+
+ /******************************************************************************/
+
+ var file_transfer_tests = 'Image File Transfer Tests ' +
+ 'The following tests should display an image of the Apache feather in the status box ' +
+ '
' +
+ '
' +
+ '
' +
+ 'Video File Transfer Tests ' +
+ 'The following tests should display a video in the status box. The video should play when play is pressed ' +
+ '
' +
+ '
';
+
+ contentEl.innerHTML = '
' +
+ file_transfer_tests;
+
+ createActionButton('Download and display img (cdvfile)', function () {
+ downloadImg(imageURL, function (entry) { return entry.toInternalURL(); }, new Image());
+ }, 'cdv_image');
+
+ createActionButton('Download and display img (native)', function () {
+ downloadImg(imageURL, function (entry) { return entry.toURL(); }, new Image());
+ }, 'native_image');
+
+ createActionButton('Download to a non-existent dir (should work)', function () {
+ downloadImg(imageURL, function (entry) { return entry.toURL(); }, new Image(), '/nonExistentDirTest/');
+ }, 'non-existent_dir');
+
+ createActionButton('Download and play video (cdvfile)', function () {
+ var videoElement = document.createElement('video');
+ videoElement.controls = "controls";
+ downloadImg(videoURL, function (entry) { return entry.toInternalURL(); }, videoElement);
+ }, 'cdv_video');
+
+ createActionButton('Download and play video (native)', function () {
+ var videoElement = document.createElement('video');
+ videoElement.controls = "controls";
+ downloadImg(videoURL, function (entry) { return entry.toURL(); }, videoElement);
+ }, 'native_video');
+};
diff --git a/plugins/cordova-plugin-file-transfer/www/FileTransfer.js b/plugins/cordova-plugin-file-transfer/www/FileTransfer.js
new file mode 100644
index 0000000..add97da
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/FileTransfer.js
@@ -0,0 +1,235 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+var argscheck = require('cordova/argscheck'),
+ exec = require('cordova/exec'),
+ FileTransferError = require('./FileTransferError'),
+ ProgressEvent = require('cordova-plugin-file.ProgressEvent');
+
+function newProgressEvent(result) {
+ var pe = new ProgressEvent();
+ pe.lengthComputable = result.lengthComputable;
+ pe.loaded = result.loaded;
+ pe.total = result.total;
+ return pe;
+}
+
+function getUrlCredentials(urlString) {
+ var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
+ credentials = credentialsPattern.exec(urlString);
+
+ return credentials && credentials[1];
+}
+
+function getBasicAuthHeader(urlString) {
+ var header = null;
+
+
+ // This is changed due to MS Windows doesn't support credentials in http uris
+ // so we detect them by regexp and strip off from result url
+ // Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem
+
+ if (window.btoa) {
+ var credentials = getUrlCredentials(urlString);
+ if (credentials) {
+ var authHeader = "Authorization";
+ var authHeaderValue = "Basic " + window.btoa(credentials);
+
+ header = {
+ name : authHeader,
+ value : authHeaderValue
+ };
+ }
+ }
+
+ 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;
+
+/**
+ * FileTransfer uploads a file to a remote server.
+ * @constructor
+ */
+var FileTransfer = function() {
+ this._id = ++idCounter;
+ this.onprogress = null; // optional callback
+};
+
+/**
+* Given an absolute file path, uploads a file on the device to a remote server
+* using a multipart HTTP request.
+* @param filePath {String} Full path of the file on the device
+* @param server {String} URL of the server to receive the file
+* @param successCallback (Function} Callback to be invoked when upload has completed
+* @param errorCallback {Function} Callback to be invoked upon error
+* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
+* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+*/
+FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
+ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
+ // check for options
+ var fileKey = null;
+ var fileName = null;
+ var mimeType = null;
+ var params = null;
+ var chunkedMode = true;
+ var headers = null;
+ var httpMethod = null;
+ var basicAuthHeader = getBasicAuthHeader(server);
+ if (basicAuthHeader) {
+ server = server.replace(getUrlCredentials(server) + '@', '');
+
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ if (options) {
+ fileKey = options.fileKey;
+ fileName = options.fileName;
+ mimeType = options.mimeType;
+ headers = options.headers;
+ httpMethod = options.httpMethod || "POST";
+ if (httpMethod.toUpperCase() == "PUT"){
+ httpMethod = "PUT";
+ } else {
+ httpMethod = "POST";
+ }
+ if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
+ chunkedMode = options.chunkedMode;
+ }
+ if (options.params) {
+ params = options.params;
+ }
+ else {
+ params = {};
+ }
+ }
+
+ 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);
+ };
+
+ var self = this;
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ self.onprogress(newProgressEvent(result));
+ }
+ } else {
+ successCallback && successCallback(result);
+ }
+ };
+ exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+};
+
+/**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ * @param source {String} URL of the server to receive the file
+ * @param target {String} Full path of the file on the device
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ * @param options {FileDownloadOptions} Optional parameters such as headers
+ */
+FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
+ argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
+ var self = this;
+
+ var basicAuthHeader = getBasicAuthHeader(source);
+ if (basicAuthHeader) {
+ source = source.replace(getUrlCredentials(source) + '@', '');
+
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var headers = null;
+ if (options) {
+ headers = options.headers || null;
+ }
+
+ if (cordova.platformId === "windowsphone" && headers) {
+ headers = convertHeadersToArray(headers);
+ }
+
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ return self.onprogress(newProgressEvent(result));
+ }
+ } else if (successCallback) {
+ var entry = null;
+ if (result.isDirectory) {
+ entry = new (require('cordova-plugin-file.DirectoryEntry'))();
+ }
+ else if (result.isFile) {
+ entry = new (require('cordova-plugin-file.FileEntry'))();
+ }
+ entry.isDirectory = result.isDirectory;
+ entry.isFile = result.isFile;
+ entry.name = result.name;
+ entry.fullPath = result.fullPath;
+ entry.filesystem = new FileSystem(result.filesystemName || (result.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
+ entry.nativeURL = result.nativeURL;
+ successCallback(entry);
+ }
+ };
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
+ errorCallback(error);
+ };
+
+ exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);
+};
+
+/**
+ * Aborts the ongoing file transfer on this object. The original error
+ * callback for the file transfer will be called if necessary.
+ */
+FileTransfer.prototype.abort = function() {
+ exec(null, null, 'FileTransfer', 'abort', [this._id]);
+};
+
+module.exports = FileTransfer;
diff --git a/plugins/cordova-plugin-file-transfer/www/FileTransferError.js b/plugins/cordova-plugin-file-transfer/www/FileTransferError.js
new file mode 100644
index 0000000..07ca831
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/FileTransferError.js
@@ -0,0 +1,41 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+/**
+ * FileTransferError
+ * @constructor
+ */
+var FileTransferError = function(code, source, target, status, body, exception) {
+ this.code = code || null;
+ this.source = source || null;
+ this.target = target || null;
+ this.http_status = status || null;
+ this.body = body || null;
+ this.exception = exception || null;
+};
+
+FileTransferError.FILE_NOT_FOUND_ERR = 1;
+FileTransferError.INVALID_URL_ERR = 2;
+FileTransferError.CONNECTION_ERR = 3;
+FileTransferError.ABORT_ERR = 4;
+FileTransferError.NOT_MODIFIED_ERR = 5;
+
+module.exports = FileTransferError;
diff --git a/plugins/cordova-plugin-file-transfer/www/blackberry10/FileTransfer.js b/plugins/cordova-plugin-file-transfer/www/blackberry10/FileTransfer.js
new file mode 100644
index 0000000..f74914a
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/blackberry10/FileTransfer.js
@@ -0,0 +1,188 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+var argscheck = require('cordova/argscheck'),
+ FileTransferError = require('./FileTransferError');
+ xhrImpl = require('./BB10XHRImplementation');
+
+
+function getBasicAuthHeader(urlString) {
+ var header = null;
+
+ if (window.btoa) {
+ // parse the url using the Location object
+ var url = document.createElement('a');
+ url.href = urlString;
+
+ var credentials = null;
+ var protocol = url.protocol + "//";
+ var origin = protocol + url.host;
+
+ // check whether there are the username:password credentials in the url
+ if (url.href.indexOf(origin) !== 0) { // credentials found
+ var atIndex = url.href.indexOf("@");
+ credentials = url.href.substring(protocol.length, atIndex);
+ }
+
+ if (credentials) {
+ var authHeader = "Authorization";
+ var authHeaderValue = "Basic " + window.btoa(credentials);
+
+ header = {
+ name : authHeader,
+ value : authHeaderValue
+ };
+ }
+ }
+
+ return header;
+}
+
+var idCounter = 0;
+
+/**
+ * FileTransfer uploads a file to a remote server.
+ * @constructor
+ */
+var FileTransfer = function() {
+ this._id = ++idCounter;
+ this.onprogress = null; // optional callback
+};
+
+/**
+* Given an absolute file path, uploads a file on the device to a remote server
+* using a multipart HTTP request.
+* @param filePath {String} Full path of the file on the device
+* @param server {String} URL of the server to receive the file
+* @param successCallback (Function} Callback to be invoked when upload has completed
+* @param errorCallback {Function} Callback to be invoked upon error
+* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
+* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+*/
+FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
+ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
+ // check for options
+ var fileKey = null;
+ var fileName = null;
+ var mimeType = null;
+ var params = null;
+ var chunkedMode = true;
+ var headers = null;
+ var httpMethod = null;
+ var basicAuthHeader = getBasicAuthHeader(server);
+ if (basicAuthHeader) {
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ if (options) {
+ fileKey = options.fileKey;
+ fileName = options.fileName;
+ mimeType = options.mimeType;
+ headers = options.headers;
+ httpMethod = options.httpMethod || "POST";
+ if (httpMethod.toUpperCase() == "PUT"){
+ httpMethod = "PUT";
+ } else {
+ httpMethod = "POST";
+ }
+ if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
+ chunkedMode = options.chunkedMode;
+ }
+ if (options.params) {
+ params = options.params;
+ }
+ else {
+ params = {};
+ }
+ }
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body);
+ errorCallback(error);
+ };
+
+ var self = this;
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ self.onprogress(result);
+ }
+ } else {
+ successCallback && successCallback(result);
+ }
+ };
+ xhrImpl.upload(win, fail, [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
+};
+
+/**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ * @param source {String} URL of the server to receive the file
+ * @param target {String} Full path of the file on the device
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ * @param options {FileDownloadOptions} Optional parameters such as headers
+ */
+FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
+ argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
+ var self = this;
+
+ var basicAuthHeader = getBasicAuthHeader(source);
+ if (basicAuthHeader) {
+ options = options || {};
+ options.headers = options.headers || {};
+ options.headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var headers = null;
+ if (options) {
+ headers = options.headers || null;
+ }
+
+ var win = function(result) {
+ if (typeof result.lengthComputable != "undefined") {
+ if (self.onprogress) {
+ return self.onprogress(result);
+ }
+ } else if (successCallback) {
+ successCallback(result);
+ }
+ };
+
+ var fail = errorCallback && function(e) {
+ var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body);
+ errorCallback(error);
+ };
+
+ xhrImpl.download(win, fail, [source, target, trustAllHosts, this._id, headers]);
+};
+
+/**
+ * Aborts the ongoing file transfer on this object. The original error
+ * callback for the file transfer will be called if necessary.
+ */
+FileTransfer.prototype.abort = function() {
+ xhrImpl.abort(null, null, [this._id]);
+};
+
+module.exports = FileTransfer;
diff --git a/plugins/cordova-plugin-file-transfer/www/blackberry10/FileTransferProxy.js b/plugins/cordova-plugin-file-transfer/www/blackberry10/FileTransferProxy.js
new file mode 100644
index 0000000..a363f07
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/blackberry10/FileTransferProxy.js
@@ -0,0 +1,36 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+/*
+ * FileTransferProxy
+ *
+ * Register all FileTransfer exec calls to be handled by proxy
+ */
+
+var xhrFileTransfer = require('cordova-plugin-file-transfer.xhrFileTransfer');
+
+module.exports = {
+ abort: xhrFileTransfer.abort,
+ download: xhrFileTransfer.download,
+ upload: xhrFileTransfer.upload
+};
+
+require('cordova/exec/proxy').add('FileTransfer', module.exports);
diff --git a/plugins/cordova-plugin-file-transfer/www/blackberry10/xhrFileTransfer.js b/plugins/cordova-plugin-file-transfer/www/blackberry10/xhrFileTransfer.js
new file mode 100644
index 0000000..7eba7af
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/blackberry10/xhrFileTransfer.js
@@ -0,0 +1,259 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+/*global Blob:false */
+var cordova = require('cordova'),
+ resolve = cordova.require('cordova-plugin-file.resolveLocalFileSystemURIProxy'),
+ requestAnimationFrame = cordova.require('cordova-plugin-file.bb10RequestAnimationFrame'),
+ xhr = {};
+
+function getParentPath(filePath) {
+ var pos = filePath.lastIndexOf('/');
+ return filePath.substring(0, pos + 1);
+}
+
+function getFileName(filePath) {
+ var pos = filePath.lastIndexOf('/');
+ return filePath.substring(pos + 1);
+}
+
+function checkURL(url) {
+ return url.indexOf(' ') === -1 ? true : false;
+}
+
+module.exports = {
+ abort: function (win, fail, args) {
+ var id = args[0];
+ if (xhr[id]) {
+ xhr[id].abort();
+ if (typeof(win) === 'function') {
+ win();
+ }
+ } else if (typeof(fail) === 'function') {
+ fail();
+ }
+ },
+
+ upload: function(win, fail, args) {
+ var filePath = args[0],
+ server = args[1],
+ fileKey = args[2],
+ fileName = args[3],
+ mimeType = args[4],
+ params = args[5],
+ /*trustAllHosts = args[6],*/
+ chunkedMode = args[7],
+ headers = args[8],
+ onSuccess = function (data) {
+ if (typeof(win) === 'function') {
+ win(data);
+ }
+ },
+ onFail = function (code) {
+ delete xhr[fileKey];
+ if (typeof(fail) === 'function') {
+ fail(code);
+ }
+ };
+
+ if (!checkURL(server)) {
+ onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, server, filePath));
+ }
+
+ xhr[fileKey] = new XMLHttpRequest();
+ xhr[fileKey].onabort = function () {
+ onFail(new FileTransferError(FileTransferError.ABORT_ERR, server, filePath, this.status, xhr[fileKey].response));
+ };
+
+ resolve(function(entry) {
+ requestAnimationFrame(function () {
+ entry.nativeEntry.file(function(file) {
+ function uploadFile(blobFile) {
+ var fd = new FormData();
+
+ fd.append(fileKey, blobFile, fileName);
+ for (var prop in params) {
+ if(params.hasOwnProperty(prop)) {
+ fd.append(prop, params[prop]);
+ }
+ }
+
+ xhr[fileKey].open("POST", server);
+ xhr[fileKey].onload = function(evt) {
+ if (xhr[fileKey].status === 200) {
+ var result = new FileUploadResult();
+ result.bytesSent = file.size;
+ result.responseCode = xhr[fileKey].status;
+ result.response = xhr[fileKey].response;
+ delete xhr[fileKey];
+ onSuccess(result);
+ } else if (xhr[fileKey].status === 404) {
+ onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
+ } else {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
+ }
+ };
+ xhr[fileKey].ontimeout = function(evt) {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
+ };
+ xhr[fileKey].onerror = function () {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, this.status, xhr[fileKey].response));
+ };
+ xhr[fileKey].upload.onprogress = function (evt) {
+ if (evt.loaded > 0) {
+ onSuccess(evt);
+ }
+ };
+
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ xhr[fileKey].setRequestHeader(header, headers[header]);
+ }
+ }
+
+ requestAnimationFrame(function () {
+ xhr[fileKey].send(fd);
+ });
+ }
+
+ var bytesPerChunk;
+ if (chunkedMode === true) {
+ bytesPerChunk = 1024 * 1024; // 1MB chunk sizes.
+ } else {
+ bytesPerChunk = file.size;
+ }
+ var start = 0;
+ var end = bytesPerChunk;
+ while (start < file.size) {
+ var chunk = file.slice(start, end, mimeType);
+ uploadFile(chunk);
+ start = end;
+ end = start + bytesPerChunk;
+ }
+ }, function(error) {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, server, filePath));
+ });
+ });
+ }, function(error) {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, server, filePath));
+ }, [filePath]);
+ },
+
+ download: function (win, fail, args) {
+ var source = args[0],
+ target = args[1],
+ id = args[3],
+ headers = args[4],
+ fileWriter,
+ onSuccess = function (entry) {
+ if (typeof(win) === 'function') {
+ win(entry);
+ }
+ },
+ onFail = function (error) {
+ var reader;
+ delete xhr[id];
+ if (typeof(fail) === 'function') {
+ if (error && error.body && typeof(error.body) === 'object') {
+ reader = new FileReader()._realReader;
+ reader.onloadend = function () {
+ error.body = this.result;
+ fail(error);
+ };
+ reader.onerror = function () {
+ fail(error);
+ };
+ reader.readAsText(error.body);
+ } else {
+ fail(error);
+ }
+ }
+ };
+
+ if (!checkURL(source)) {
+ onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, source, target));
+ }
+
+ xhr[id] = new XMLHttpRequest();
+
+ function writeFile(entry) {
+ entry.createWriter(function (writer) {
+ fileWriter = writer;
+ fileWriter.onwriteend = function (evt) {
+ if (!evt.target.error) {
+ entry.filesystemName = entry.filesystem.name;
+ delete xhr[id];
+ onSuccess(entry);
+ } else {
+ onFail(evt.target.error);
+ }
+ };
+ fileWriter.onerror = function (evt) {
+ onFail(evt.target.error);
+ };
+ fileWriter.write(new Blob([xhr[id].response]));
+ }, function (error) {
+ onFail(error);
+ });
+ }
+
+ xhr[id].onerror = function (e) {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, source, target, xhr[id].status, xhr[id].response));
+ };
+
+ xhr[id].onabort = function (e) {
+ onFail(new FileTransferError(FileTransferError.ABORT_ERR, source, target, xhr[id].status, xhr[id].response));
+ }
+
+ xhr[id].onload = function () {
+ if (xhr[id].readyState === xhr[id].DONE) {
+ if (xhr[id].status === 200 && xhr[id].response) {
+ resolveLocalFileSystemURI(getParentPath(target), function (dir) {
+ dir.getFile(getFileName(target), {create: true}, writeFile, function (error) {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, source, target, xhr[id].status, xhr[id].response));
+ });
+ }, function (error) {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, source, target, xhr[id].status, xhr[id].response));
+ });
+ } else if (xhr[id].status === 404) {
+ onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, source, target, xhr[id].status, xhr[id].response));
+ } else {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, source, target, xhr[id].status, xhr[id].response));
+ }
+ }
+ };
+ xhr[id].onprogress = function (evt) {
+ onSuccess(evt);
+ };
+ xhr[id].open("GET", source, true);
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ xhr[id].setRequestHeader(header, headers[header]);
+ }
+ }
+ xhr[id].responseType = "blob";
+ requestAnimationFrame(function () {
+ if (xhr[id]) {
+ xhr[id].send();
+ }
+ });
+ }
+};
diff --git a/plugins/cordova-plugin-file-transfer/www/browser/FileTransfer.js b/plugins/cordova-plugin-file-transfer/www/browser/FileTransfer.js
new file mode 100644
index 0000000..2146ed1
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/browser/FileTransfer.js
@@ -0,0 +1,328 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+/*global module, require*/
+
+var argscheck = require('cordova/argscheck'),
+ FileTransferError = require('./FileTransferError');
+
+function getParentPath(filePath) {
+ var pos = filePath.lastIndexOf('/');
+ return filePath.substring(0, pos + 1);
+}
+
+function getFileName(filePath) {
+ var pos = filePath.lastIndexOf('/');
+ return filePath.substring(pos + 1);
+}
+
+function getUrlCredentials(urlString) {
+ var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
+ credentials = credentialsPattern.exec(urlString);
+
+ return credentials && credentials[1];
+}
+
+function getBasicAuthHeader(urlString) {
+ var header = null;
+
+
+ // This is changed due to MS Windows doesn't support credentials in http uris
+ // so we detect them by regexp and strip off from result url
+ // Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem
+
+ if (window.btoa) {
+ var credentials = getUrlCredentials(urlString);
+ if (credentials) {
+ var authHeader = "Authorization";
+ var authHeaderValue = "Basic " + window.btoa(credentials);
+
+ header = {
+ name : authHeader,
+ value : authHeaderValue
+ };
+ }
+ }
+
+ return header;
+}
+
+function checkURL(url) {
+ return url.indexOf(' ') === -1 ? true : false;
+}
+
+var idCounter = 0;
+
+var transfers = {};
+
+/**
+ * FileTransfer uploads a file to a remote server.
+ * @constructor
+ */
+var FileTransfer = function() {
+ this._id = ++idCounter;
+ this.onprogress = null; // optional callback
+};
+
+/**
+ * Given an absolute file path, uploads a file on the device to a remote server
+ * using a multipart HTTP request.
+ * @param filePath {String} Full path of the file on the device
+ * @param server {String} URL of the server to receive the file
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param options {FileUploadOptions} Optional parameters such as file name and mimetype
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ */
+FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options) {
+ // check for arguments
+ argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
+
+ // Check if target URL doesn't contain spaces. If contains, it should be escaped first
+ // (see https://github.com/apache/cordova-plugin-file-transfer/blob/master/doc/index.md#upload)
+ if (!checkURL(server)) {
+ errorCallback && errorCallback(new FileTransferError(FileTransferError.INVALID_URL_ERR, filePath, server));
+ return;
+ }
+
+ options = options || {};
+
+ var fileKey = options.fileKey || "file";
+ var fileName = options.fileName || "image.jpg";
+ var mimeType = options.mimeType || "image/jpeg";
+ var params = options.params || {};
+ var withCredentials = options.withCredentials || false;
+ // var chunkedMode = !!options.chunkedMode; // Not supported
+ var headers = options.headers || {};
+ var httpMethod = options.httpMethod && options.httpMethod.toUpperCase() === "PUT" ? "PUT" : "POST";
+
+ var basicAuthHeader = getBasicAuthHeader(server);
+ if (basicAuthHeader) {
+ server = server.replace(getUrlCredentials(server) + '@', '');
+ headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var that = this;
+ var xhr = transfers[this._id] = new XMLHttpRequest();
+ xhr.withCredentials = withCredentials;
+
+ var fail = errorCallback && function(code, status, response) {
+ transfers[this._id] && delete transfers[this._id];
+ var error = new FileTransferError(code, filePath, server, status, response);
+ errorCallback && errorCallback(error);
+ };
+
+ window.resolveLocalFileSystemURL(filePath, function(entry) {
+ entry.file(function(file) {
+ var reader = new FileReader();
+ reader.onloadend = function() {
+ var blob = new Blob([this.result], {type: mimeType});
+
+ // Prepare form data to send to server
+ var fd = new FormData();
+ fd.append(fileKey, blob, fileName);
+ for (var prop in params) {
+ if (params.hasOwnProperty(prop)) {
+ fd.append(prop, params[prop]);
+ }
+ }
+
+ xhr.open(httpMethod, server);
+
+ // Fill XHR headers
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ xhr.setRequestHeader(header, headers[header]);
+ }
+ }
+
+ xhr.onload = function() {
+ if (this.status === 200) {
+ var result = new FileUploadResult(); // jshint ignore:line
+ result.bytesSent = blob.size;
+ result.responseCode = this.status;
+ result.response = this.response;
+ delete transfers[that._id];
+ successCallback(result);
+ } else if (this.status === 404) {
+ fail(FileTransferError.INVALID_URL_ERR, this.status, this.response);
+ } else {
+ fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
+ }
+ };
+
+ xhr.ontimeout = function() {
+ fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
+ };
+
+ xhr.onerror = function() {
+ fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
+ };
+
+ xhr.onabort = function () {
+ fail(FileTransferError.ABORT_ERR, this.status, this.response);
+ };
+
+ xhr.upload.onprogress = function (e) {
+ that.onprogress && that.onprogress(e);
+ };
+
+ xhr.send(fd);
+ // Special case when transfer already aborted, but XHR isn't sent.
+ // In this case XHR won't fire an abort event, so we need to check if transfers record
+ // isn't deleted by filetransfer.abort and if so, call XHR's abort method again
+ if (!transfers[that._id]) {
+ xhr.abort();
+ }
+ };
+ reader.readAsArrayBuffer(file);
+ }, function() {
+ fail(FileTransferError.FILE_NOT_FOUND_ERR);
+ });
+ }, function() {
+ fail(FileTransferError.FILE_NOT_FOUND_ERR);
+ });
+};
+
+/**
+ * Downloads a file form a given URL and saves it to the specified directory.
+ * @param source {String} URL of the server to receive the file
+ * @param target {String} Full path of the file on the device
+ * @param successCallback (Function} Callback to be invoked when upload has completed
+ * @param errorCallback {Function} Callback to be invoked upon error
+ * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
+ * @param options {FileDownloadOptions} Optional parameters such as headers
+ */
+FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
+ argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
+
+ // Check if target URL doesn't contain spaces. If contains, it should be escaped first
+ // (see https://github.com/apache/cordova-plugin-file-transfer/blob/master/doc/index.md#download)
+ if (!checkURL(source)) {
+ errorCallback && errorCallback(new FileTransferError(FileTransferError.INVALID_URL_ERR, source, target));
+ return;
+ }
+
+ options = options || {};
+
+ var headers = options.headers || {};
+ var withCredentials = options.withCredentials || false;
+
+ var basicAuthHeader = getBasicAuthHeader(source);
+ if (basicAuthHeader) {
+ source = source.replace(getUrlCredentials(source) + '@', '');
+ headers[basicAuthHeader.name] = basicAuthHeader.value;
+ }
+
+ var that = this;
+ var xhr = transfers[this._id] = new XMLHttpRequest();
+ xhr.withCredentials = withCredentials;
+ var fail = errorCallback && function(code, status, response) {
+ transfers[that._id] && delete transfers[that._id];
+ // In XHR GET reqests we're setting response type to Blob
+ // but in case of error we need to raise event with plain text response
+ if (response instanceof Blob) {
+ var reader = new FileReader();
+ reader.readAsText(response);
+ reader.onloadend = function(e) {
+ var error = new FileTransferError(code, source, target, status, e.target.result);
+ errorCallback(error);
+ };
+ } else {
+ var error = new FileTransferError(code, source, target, status, response);
+ errorCallback(error);
+ }
+ };
+
+ xhr.onload = function (e) {
+
+ var fileNotFound = function () {
+ fail(FileTransferError.FILE_NOT_FOUND_ERR);
+ };
+
+ var req = e.target;
+ // req.status === 0 is special case for local files with file:// URI scheme
+ if ((req.status === 200 || req.status === 0) && req.response) {
+ window.resolveLocalFileSystemURL(getParentPath(target), function (dir) {
+ dir.getFile(getFileName(target), {create: true}, function writeFile(entry) {
+ entry.createWriter(function (fileWriter) {
+ fileWriter.onwriteend = function (evt) {
+ if (!evt.target.error) {
+ entry.filesystemName = entry.filesystem.name;
+ delete transfers[that._id];
+ successCallback && successCallback(entry);
+ } else {
+ fail(FileTransferError.FILE_NOT_FOUND_ERR);
+ }
+ };
+ fileWriter.onerror = function () {
+ fail(FileTransferError.FILE_NOT_FOUND_ERR);
+ };
+ fileWriter.write(req.response);
+ }, fileNotFound);
+ }, fileNotFound);
+ }, fileNotFound);
+ } else if (req.status === 404) {
+ fail(FileTransferError.INVALID_URL_ERR, req.status, req.response);
+ } else {
+ fail(FileTransferError.CONNECTION_ERR, req.status, req.response);
+ }
+ };
+
+ xhr.onprogress = function (e) {
+ that.onprogress && that.onprogress(e);
+ };
+
+ xhr.onerror = function () {
+ fail(FileTransferError.CONNECTION_ERR, this.status, this.response);
+ };
+
+ xhr.onabort = function () {
+ fail(FileTransferError.ABORT_ERR, this.status, this.response);
+ };
+
+ xhr.open("GET", source, true);
+
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ xhr.setRequestHeader(header, headers[header]);
+ }
+ }
+
+ xhr.responseType = "blob";
+
+ xhr.send();
+};
+
+/**
+ * Aborts the ongoing file transfer on this object. The original error
+ * callback for the file transfer will be called if necessary.
+ */
+FileTransfer.prototype.abort = function() {
+ if (this instanceof FileTransfer) {
+ if (transfers[this._id]) {
+ transfers[this._id].abort();
+ delete transfers[this._id];
+ }
+ }
+};
+
+module.exports = FileTransfer;
diff --git a/plugins/cordova-plugin-file-transfer/www/firefoxos/FileTransferProxy.js b/plugins/cordova-plugin-file-transfer/www/firefoxos/FileTransferProxy.js
new file mode 100644
index 0000000..164da1a
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/firefoxos/FileTransferProxy.js
@@ -0,0 +1,223 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+var cordova = require('cordova'),
+ FileTransferError = require('./FileTransferError'),
+ xhr = {};
+
+function getParentPath(filePath) {
+ var pos = filePath.lastIndexOf('/');
+ return filePath.substring(0, pos + 1);
+}
+
+function getFileName(filePath) {
+ var pos = filePath.lastIndexOf('/');
+ return filePath.substring(pos + 1);
+}
+
+module.exports = {
+ abort: function (successCallback, errorCallback, args) {
+ var id = args[0];
+ if (xhr[id]) {
+ xhr[id].abort();
+ if (typeof(successCallback) === 'function') {
+ successCallback();
+ }
+ } else if (typeof(errorCallback) === 'function') {
+ errorCallback();
+ }
+ },
+
+ upload: function(successCallback, errorCallback, args) {
+ var filePath = args[0],
+ server = args[1],
+ fileKey = args[2],
+ fileName = args[3],
+ mimeType = args[4],
+ params = args[5],
+ /*trustAllHosts = args[6],*/
+ /*chunkedMode = args[7],*/
+ headers = args[8];
+
+ xhr[fileKey] = new XMLHttpRequest({mozSystem: true});
+ xhr[fileKey].onabort = function() {
+ onFail(new FileTransferError(FileTransferError.ABORT_ERR, server, filePath, this.status, xhr[fileKey].response));
+ };
+
+ window.resolveLocalFileSystemURL(filePath, function(entry) {
+ entry.file(function(file) {
+ var reader = new FileReader();
+
+ reader.onloadend = function() {
+ var blob = new Blob([this.result], {type: mimeType});
+ var fd = new FormData();
+
+ fd.append(fileKey, blob, fileName);
+
+ for (var prop in params) {
+ if (params.hasOwnProperty(prop)) {
+ fd.append(prop, params[prop]);
+ }
+ }
+
+ xhr[fileKey].open("POST", server);
+
+ xhr[fileKey].onload = function(evt) {
+ if (xhr[fileKey].status === 200) {
+ var result = new FileUploadResult();
+ result.bytesSent = blob.size;
+ result.responseCode = xhr[fileKey].status;
+ result.response = xhr[fileKey].response;
+ delete xhr[fileKey];
+ onSuccess(result);
+ } else if (xhr[fileKey].status === 404) {
+ onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
+ } else {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
+ }
+ };
+
+ xhr[fileKey].ontimeout = function() {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, xhr[fileKey].status, xhr[fileKey].response));
+ };
+
+ xhr[fileKey].onerror = function() {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, server, filePath, this.status, xhr[fileKey].response));
+ };
+
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ xhr[fileKey].setRequestHeader(header, headers[header]);
+ }
+ }
+
+ xhr[fileKey].send(fd);
+ };
+
+ reader.readAsArrayBuffer(file);
+
+ }, function() {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, server, filePath));
+ });
+ }, function() {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, server, filePath));
+ });
+
+ function onSuccess(data) {
+ if (typeof(successCallback) === 'function') {
+ successCallback(data);
+ }
+ }
+
+ function onFail(code) {
+ delete xhr[fileKey];
+ if (typeof(errorCallback) === 'function') {
+ errorCallback(code);
+ }
+ }
+ },
+
+ download: function (successCallback, errorCallback, args) {
+ var source = args[0],
+ target = args[1],
+ id = args[3],
+ headers = args[4];
+
+ xhr[id] = new XMLHttpRequest({mozSystem: true});
+
+ xhr[id].onload = function () {
+ if (xhr[id].readyState === xhr[id].DONE) {
+ if (xhr[id].status === 200 && xhr[id].response) {
+ window.resolveLocalFileSystemURL(getParentPath(target), function (dir) {
+ dir.getFile(getFileName(target), {create: true}, writeFile, function (error) {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, source, target, xhr[id].status, xhr[id].response));
+ });
+ }, function () {
+ onFail(new FileTransferError(FileTransferError.FILE_NOT_FOUND_ERR, source, target, xhr[id].status, xhr[id].response));
+ });
+ } else if (xhr[id].status === 404) {
+ onFail(new FileTransferError(FileTransferError.INVALID_URL_ERR, source, target, xhr[id].status, xhr[id].response));
+ } else {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, source, target, xhr[id].status, xhr[id].response));
+ }
+ }
+ };
+
+ function writeFile(entry) {
+ entry.createWriter(function (fileWriter) {
+ fileWriter.onwriteend = function (evt) {
+ if (!evt.target.error) {
+ entry.filesystemName = entry.filesystem.name;
+ delete xhr[id];
+ onSuccess(entry);
+ } else {
+ onFail(evt.target.error);
+ }
+ };
+ fileWriter.onerror = function (evt) {
+ onFail(evt.target.error);
+ };
+ fileWriter.write(new Blob([xhr[id].response]));
+ }, function (error) {
+ onFail(error);
+ });
+ }
+
+ xhr[id].onerror = function (e) {
+ onFail(new FileTransferError(FileTransferError.CONNECTION_ERR, source, target, xhr[id].status, xhr[id].response));
+ };
+
+ xhr[id].onabort = function (e) {
+ onFail(new FileTransferError(FileTransferError.ABORT_ERR, source, target, xhr[id].status, xhr[id].response));
+ };
+
+ xhr[id].open("GET", source, true);
+
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ xhr[id].setRequestHeader(header, headers[header]);
+ }
+ }
+
+ xhr[id].responseType = "blob";
+
+ setTimeout(function () {
+ if (xhr[id]) {
+ xhr[id].send();
+ }
+ }, 0);
+
+ function onSuccess(entry) {
+ if (typeof(successCallback) === 'function') {
+ successCallback(entry);
+ }
+ }
+
+ function onFail(error) {
+ delete xhr[id];
+ if (typeof(errorCallback) === 'function') {
+ errorCallback(error);
+ }
+ }
+ }
+};
+
+require('cordova/exec/proxy').add('FileTransfer', module.exports);
diff --git a/plugins/cordova-plugin-file-transfer/www/wp7/base64.js b/plugins/cordova-plugin-file-transfer/www/wp7/base64.js
new file mode 100644
index 0000000..6c211e7
--- /dev/null
+++ b/plugins/cordova-plugin-file-transfer/www/wp7/base64.js
@@ -0,0 +1,71 @@
+/*
+ *
+ * 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.
+ *
+*/
+
+var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
+ INVALID_CHARACTER_ERR = (function () {
+ // fabricate a suitable error object
+ try { document.createElement('$'); }
+ catch (error) { return error; }
+ }());
+
+ // encoder
+ // [https://gist.github.com/999166] by [https://github.com/nignag]
+ window.btoa || (
+ window.btoa = function (input) {
+ for (
+ // initialize result and counter
+ var block, charCode, idx = 0, map = chars, output = '';
+ // if the next input index does not exist:
+ // change the mapping table to "="
+ // check if d has no fractional digits
+ input.charAt(idx | 0) || (map = '=', idx % 1) ;
+ // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
+ output += map.charAt(63 & block >> 8 - idx % 1 * 8)
+ ) {
+ charCode = input.charCodeAt(idx += 3 / 4);
+ if (charCode > 0xFF) throw INVALID_CHARACTER_ERR;
+ block = block << 8 | charCode;
+ }
+ return output;
+ });
+
+ // decoder
+ // [https://gist.github.com/1020396] by [https://github.com/atk]
+ window.atob || (
+ window.atob = function (input) {
+ input = input.replace(/=+$/, '')
+ if (input.length % 4 == 1) throw INVALID_CHARACTER_ERR;
+ for (
+ // initialize result and counters
+ var bc = 0, bs, buffer, idx = 0, output = '';
+ // get next character
+ buffer = input.charAt(idx++) ;
+ // character found in table? initialize bit storage and add its ascii value;
+ ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
+ // and if not first of each 4 characters,
+ // convert the first 8 bits to one ascii character
+ bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
+ ) {
+ // try to find character in table (0-63, not found => -1)
+ buffer = chars.indexOf(buffer);
+ }
+ return output;
+ });
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/CONTRIBUTING.md b/plugins/cordova-plugin-file/CONTRIBUTING.md
new file mode 100644
index 0000000..f7dbcab
--- /dev/null
+++ b/plugins/cordova-plugin-file/CONTRIBUTING.md
@@ -0,0 +1,37 @@
+
+
+# Contributing to Apache Cordova
+
+Anyone can contribute to Cordova. And we need your contributions.
+
+There are multiple ways to contribute: report bugs, improve the docs, and
+contribute code.
+
+For instructions on this, start with the
+[contribution overview](http://cordova.apache.org/#contribute).
+
+The details are explained there, but the important items are:
+ - Sign and submit an Apache ICLA (Contributor License Agreement).
+ - Have a Jira issue open that corresponds to your contribution.
+ - Run the tests so your patch doesn't break existing functionality.
+
+We look forward to your contributions!
diff --git a/plugins/cordova-plugin-file/LICENSE b/plugins/cordova-plugin-file/LICENSE
new file mode 100644
index 0000000..7a4a3ea
--- /dev/null
+++ b/plugins/cordova-plugin-file/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed 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.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/NOTICE b/plugins/cordova-plugin-file/NOTICE
new file mode 100644
index 0000000..8ec56a5
--- /dev/null
+++ b/plugins/cordova-plugin-file/NOTICE
@@ -0,0 +1,5 @@
+Apache Cordova
+Copyright 2012 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/plugins/cordova-plugin-file/README.md b/plugins/cordova-plugin-file/README.md
new file mode 100644
index 0000000..ffb4e0b
--- /dev/null
+++ b/plugins/cordova-plugin-file/README.md
@@ -0,0 +1,450 @@
+
+
+# cordova-plugin-file
+
+This plugin implements a File API allowing read/write access to files residing on the device.
+
+This plugin is based on several specs, including :
+The HTML5 File API
+[http://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/)
+
+The (now-defunct) Directories and System extensions
+Latest:
+[http://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)
+Although most of the plugin code was written when an earlier spec was current:
+[http://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/)
+
+It also implements the FileWriter spec :
+[http://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html)
+
+For usage, please refer to HTML5 Rocks' excellent [FileSystem article.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+For an overview of other storage options, refer to Cordova's
+[storage guide](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+This plugin defines global `cordova.file` object.
+
+Although in the global scope, it is not available until after the `deviceready` event.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+## Installation
+
+ cordova plugin add cordova-plugin-file
+
+## Supported Platforms
+
+- Amazon Fire OS
+- Android
+- BlackBerry 10
+- Firefox OS
+- iOS
+- Windows Phone 7 and 8*
+- Windows 8*
+- Windows*
+- Browser
+
+\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._
+
+## Where to Store Files
+
+As of v1.2.0, URLs to important file-system directories are provided.
+Each URL is in the form _file:///path/to/spot/_, and can be converted to a
+`DirectoryEntry` using `window.resolveLocalFileSystemURL()`.
+
+* `cordova.file.applicationDirectory` - Read-only directory where the application
+ is installed. (_iOS_, _Android_, _BlackBerry 10_)
+
+* `cordova.file.applicationStorageDirectory` - Root directory of the application's
+ sandbox; on iOS this location is read-only (but specific subdirectories [like
+ `/Documents`] are read-write). All data contained within is private to the app. (
+ _iOS_, _Android_, _BlackBerry 10_)
+
+* `cordova.file.dataDirectory` - Persistent and private data storage within the
+ application's sandbox using internal memory (on Android, if you need to use
+ external memory, use `.externalDataDirectory`). On iOS, this directory is not
+ synced with iCloud (use `.syncedDataDirectory`). (_iOS_, _Android_, _BlackBerry 10_)
+
+* `cordova.file.cacheDirectory` - Directory for cached data files or any files
+ that your app can re-create easily. The OS may delete these files when the device
+ runs low on storage, nevertheless, apps should not rely on the OS to delete files
+ in here. (_iOS_, _Android_, _BlackBerry 10_)
+
+* `cordova.file.externalApplicationStorageDirectory` - Application space on
+ external storage. (_Android_)
+
+* `cordova.file.externalDataDirectory` - Where to put app-specific data files on
+ external storage. (_Android_)
+
+* `cordova.file.externalCacheDirectory` - Application cache on external storage.
+ (_Android_)
+
+* `cordova.file.externalRootDirectory` - External storage (SD card) root. (_Android_, _BlackBerry 10_)
+
+* `cordova.file.tempDirectory` - Temp directory that the OS can clear at will. Do not
+ rely on the OS to clear this directory; your app should always remove files as
+ applicable. (_iOS_)
+
+* `cordova.file.syncedDataDirectory` - Holds app-specific files that should be synced
+ (e.g. to iCloud). (_iOS_)
+
+* `cordova.file.documentsDirectory` - Files private to the app, but that are meaningful
+ to other application (e.g. Office files). (_iOS_)
+
+* `cordova.file.sharedDirectory` - Files globally available to all applications (_BlackBerry 10_)
+
+## File System Layouts
+
+Although technically an implementation detail, it can be very useful to know how
+the `cordova.file.*` properties map to physical paths on a real device.
+
+### iOS File System Layout
+
+| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | persistent? | OS clears | sync | private |
+|:-----------------------------------------------|:----------------------------|:----------------------|:----:|:-----------:|:---------:|:----:|:-------:|
+| `/var/mobile/Applications//` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Yes |
+| `appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Yes |
+| `www/` | - | - | r | N/A | N/A | N/A | Yes |
+| `Documents/` | documentsDirectory | documents | r/w | Yes | No | Yes | Yes |
+| `NoCloud/` | - | documents-nosync | r/w | Yes | No | No | Yes |
+| `Library` | - | library | r/w | Yes | No | Yes? | Yes |
+| `NoCloud/` | dataDirectory | library-nosync | r/w | Yes | No | No | Yes |
+| `Cloud/` | syncedDataDirectory | - | r/w | Yes | No | Yes | Yes |
+| `Caches/` | cacheDirectory | cache | r/w | Yes* | Yes\*\*\*| No | Yes |
+| `tmp/` | tempDirectory | - | r/w | No\*\* | Yes\*\*\*| No | Yes |
+
+
+ \* Files persist across app restarts and upgrades, but this directory can
+ be cleared whenever the OS desires. Your app should be able to recreate any
+ content that might be deleted.
+
+\*\* Files may persist across app restarts, but do not rely on this behavior. Files
+ are not guaranteed to persist across updates. Your app should remove files from
+ this directory when it is applicable, as the OS does not guarantee when (or even
+ if) these files are removed.
+
+\*\*\* The OS may clear the contents of this directory whenever it feels it is
+ necessary, but do not rely on this. You should clear this directory as
+ appropriate for your application.
+
+### Android File System Layout
+
+| Device Path | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistent? | OS clears | private |
+|:------------------------------------------------|:----------------------------|:--------------------------|:----:|:-----------:|:---------:|:-------:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Yes |
+| `/data/data//` | applicationStorageDirectory | - | r/w | N/A | N/A | Yes |
+| `cache` | cacheDirectory | cache | r/w | Yes | Yes\* | Yes |
+| `files` | dataDirectory | files | r/w | Yes | No | Yes |
+| `Documents` | | documents | r/w | Yes | No | Yes |
+| `/` | externalRootDirectory | sdcard | r/w | Yes | No | No |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Yes | No | No |
+| `cache` | externalCacheDirectry | cache-external | r/w | Yes | No\*\*| No |
+| `files` | externalDataDirectory | files-external | r/w | Yes | No | No |
+
+\* The OS may periodically clear this directory, but do not rely on this behavior. Clear
+ the contents of this directory as appropriate for your application. Should a user
+ purge the cache manually, the contents of this directory are removed.
+
+\*\* The OS does not clear this directory automatically; you are responsible for managing
+ the contents yourself. Should the user purge the cache manually, the contents of the
+ directory are removed.
+
+**Note**: If external storage can't be mounted, the `cordova.file.external*`
+properties are `null`.
+
+### BlackBerry 10 File System Layout
+
+| Device Path | `cordova.file.*` | r/w? | persistent? | OS clears | private |
+|:-------------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
+| `file:///accounts/1000/appdata//` | applicationStorageDirectory | r | N/A | N/A | Yes |
+| `app/native` | applicationDirectory | r | N/A | N/A | Yes |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Yes | Yes |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Yes | No | Yes |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | Yes | No | No |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | Yes | No | No |
+
+*Note*: When application is deployed to work perimeter, all paths are relative to /accounts/1000-enterprise.
+
+## Android Quirks
+
+### Android Persistent storage location
+
+There are multiple valid locations to store persistent files on an Android
+device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html)
+for an extensive discussion of the various possibilities.
+
+Previous versions of the plugin would choose the location of the temporary and
+persistent files on startup, based on whether the device claimed that the SD
+Card (or equivalent storage partition) was mounted. If the SD Card was mounted,
+or if a large internal storage partition was available (such as on Nexus
+devices,) then the persistent files would be stored in the root of that space.
+This meant that all Cordova apps could see all of the files available on the
+card.
+
+If the SD card was not available, then previous versions would store data under
+`/data/data/`, which isolates apps from each other, but may still
+cause data to be shared between users.
+
+It is now possible to choose whether to store files in the internal file
+storage location, or using the previous logic, with a preference in your
+application's `config.xml` file. To do this, add one of these two lines to
+`config.xml`:
+
+
+
+
+
+Without this line, the File plugin will use `Internal` as the default. If
+a preference tag is present, and is not one of these values, the application
+will not start.
+
+If your application has previously been shipped to users, using an older (pre-
+3.0.0) version of this plugin, and has stored files in the persistent filesystem,
+then you should set the preference to `Compatibility` if your config.xml does not specify a location for the persistent filesystem. Switching the location to
+"Internal" would mean that existing users who upgrade their application may be
+unable to access their previously-stored files, depending on their device.
+
+If your application is new, or has never previously stored files in the
+persistent filesystem, then the `Internal` setting is generally recommended.
+
+### Slow recursive operations for /android_asset
+
+Listing asset directories is really slow on Android. You can speed it up though, by
+adding `src/android/build-extras.gradle` to the root of your android project (also
+requires cordova-android@4.0.0 or greater).
+
+## iOS Quirks
+
+- `cordova.file.applicationStorageDirectory` is read-only; attempting to store
+ files within the root directory will fail. Use one of the other `cordova.file.*`
+ properties defined for iOS (only `applicationDirectory` and `applicationStorageDirectory` are
+ read-only).
+- `FileReader.readAsText(blob, encoding)`
+ - The `encoding` parameter is not supported, and UTF-8 encoding is always in effect.
+
+### iOS Persistent storage location
+
+There are two valid locations to store persistent files on an iOS device: the
+Documents directory and the Library directory. Previous versions of the plugin
+only ever stored persistent files in the Documents directory. This had the
+side-effect of making all of an application's files visible in iTunes, which
+was often unintended, especially for applications which handle lots of small
+files, rather than producing complete documents for export, which is the
+intended purpose of the directory.
+
+It is now possible to choose whether to store files in the documents or library
+directory, with a preference in your application's `config.xml` file. To do this,
+add one of these two lines to `config.xml`:
+
+
+
+
+
+Without this line, the File plugin will use `Compatibility` as the default. If
+a preference tag is present, and is not one of these values, the application
+will not start.
+
+If your application has previously been shipped to users, using an older (pre-
+1.0) version of this plugin, and has stored files in the persistent filesystem,
+then you should set the preference to `Compatibility`. Switching the location to
+`Library` would mean that existing users who upgrade their application would be
+unable to access their previously-stored files.
+
+If your application is new, or has never previously stored files in the
+persistent filesystem, then the `Library` setting is generally recommended.
+
+## Firefox OS Quirks
+
+The File System API is not natively supported by Firefox OS and is implemented
+as a shim on top of indexedDB.
+
+* Does not fail when removing non-empty directories
+* Does not support metadata for directories
+* Methods `copyTo` and `moveTo` do not support directories
+
+The following data paths are supported:
+* `applicationDirectory` - Uses `xhr` to get local files that are packaged with the app.
+* `dataDirectory` - For persistent app-specific data files.
+* `cacheDirectory` - Cached files that should survive app restarts (Apps should not rely
+on the OS to delete files in here).
+
+## Browser Quirks
+
+### Common quirks and remarks
+- Each browser uses its own sandboxed filesystem. IE and Firefox use IndexedDB as a base.
+All browsers use forward slash as directory separator in a path.
+- Directory entries have to be created successively.
+For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)`
+will fail if dir1 did not exist.
+- The plugin requests user permission to use persistent storage at the application first start.
+- Plugin supports `cdvfile://localhost` (local resources) only. I.e. external resources are not supported via `cdvfile`.
+- 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).
+- Blob and File' `close` function is not supported.
+- `FileSaver` and `BlobBuilder` are not supported by this plugin and don't have stubs.
+- The plugin does not support `requestAllFileSystems`. This function is also missing in the specifications.
+- Entries in directory will not be removed if you use `create: true` flag for existing directory.
+- Files created via constructor are not supported. You should use entry.file method instead.
+- Each browser uses its own form for blob URL references.
+- `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension,
+mediatype in IE is always empty (which is the same as `text-plain` according the specification),
+the mediatype in Firefox is always `application/octet-stream`.
+For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`,
+IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:;base64,YWJjZGVmZw==`.
+- `toInternalURL` returns the path in the form `file:///persistent/path/to/entry` (Firefox, IE).
+Chrome returns the path in the form `cdvfile://localhost/persistent/file`.
+
+### Chrome quirks
+- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to `filePluginIsReady` event.
+Example:
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+You can use `window.isFilePluginReadyRaised` function to check whether event was already raised.
+- window.requestFileSystem TEMPORARY and PERSISTENT filesystem quotas are not limited in Chrome.
+- To increase persistent storage in Chrome you need to call `window.initPersistentFileSystem` method. Persistent storage quota is 5 MB by default.
+- Chrome requires `--allow-file-access-from-files` run argument to support API via `file:///` protocol.
+- `File` object will be not changed if you use flag `{create:true}` when getting an existing `Entry`.
+- 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).
+- `toURL` function in Chrome returns `filesystem:`-prefixed path depending on application host.
+For example, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`.
+- `toURL` function result does not contain trailing slash in case of directory entry.
+Chrome resolves directories with slash-trailed urls correctly though.
+- `resolveLocalFileSystemURL` method requires the inbound `url` to have `filesystem` prefix. For example, `url` parameter for `resolveLocalFileSystemURL`
+should be in the form `filesystem:file:///persistent/somefile.txt` as opposed to the form `file:///persistent/somefile.txt` in Android.
+- Deprecated `toNativeURL` function is not supported and does not have a stub.
+- `setMetadata` function is not stated in the specifications and not supported.
+- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) on requesting of a non-existant filesystem.
+- 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.
+- 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.
+- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) on trying to moveTo directory that does not exist.
+
+### IndexedDB-based impl quirks (Firefox and IE)
+- `.` and `..` are not supported.
+- IE does not support `file:///`-mode; only hosted mode is supported (http://localhost:xxxx).
+- Firefox filesystem size is not limited but each 50MB extension will request a user permission.
+IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation of filesystem without prompting,
+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.
+So `size` parameter for `requestFileSystem` function does not affect filesystem in Firefox and IE.
+- `readAsBinaryString` function is not stated in the Specs and not supported in IE and does not have a stub.
+- `file.type` is always null.
+- You should not create entry using DirectoryEntry instance callback result which was deleted.
+Otherwise, you will get a 'hanging entry'.
+- Before you can read a file, which was just written you need to get a new instance of this file.
+- `setMetadata` function, which is not stated in the Specs supports `modificationTime` field change only.
+- `copyTo` and `moveTo` functions do not support directories.
+- Directories metadata is not supported.
+- Both Entry.remove and directoryEntry.removeRecursively don't fail when removing
+non-empty directories - directories being removed are cleaned along with contents instead.
+- `abort` and `truncate` functions are not supported.
+- progress events are not fired. For example, this handler will be not executed:
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## Upgrading Notes
+
+In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed,
+to be more in line with the published specification.
+
+Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location
+in the `fullPath` property of `Entry` objects. These paths would typically look like
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+These paths were also returned by the `toURL()` method of the `Entry` objects.
+
+With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of
+the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry`
+object with a `fullPath` of
+
+ /path/to/file
+
+If your application works with device-absolute-paths, and you previously retrieved those
+paths through the `fullPath` property of `Entry` objects, then you should update your code
+to use `entry.toURL()` instead.
+
+For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a
+device-absolute-path, and will return an `Entry` object corresponding to it, as long as that
+file exists within either the `TEMPORARY` or `PERSISTENT` filesystems.
+
+This has particularly been an issue with the File-Transfer plugin, which previously used
+device-absolute-paths (and can still accept them). It has been updated to work correctly
+with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any
+issues getting that plugin to work with files on the device.
+
+In v1.1.0 the return value of `toURL()` was changed (see [CB-6394] (https://issues.apache.org/jira/browse/CB-6394))
+to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use `toInternalURL()` now.
+This method will now return filesystem URLs of the form
+
+ cdvfile://localhost/persistent/path/to/file
+
+which can be used to identify the file uniquely.
+
+## List of Error Codes and Meanings
+When an error is thrown, one of the following codes will be used.
+
+| Code | Constant |
+|-----:|:------------------------------|
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configuring the Plugin (Optional)
+
+The set of available filesystems can be configured per-platform. Both iOS and
+Android recognize a tag in `config.xml` which names the
+filesystems to be installed. By default, all file-system roots are enabled.
+
+
+
+
+### Android
+
+* `files`: The application's internal file storage directory
+* `files-external`: The application's external file storage directory
+* `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.
+* `cache`: The application's internal cache directory
+* `cache-external`: The application's external cache directory
+* `root`: The entire device filesystem
+
+Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
+
+### iOS
+
+* `library`: The application's Library directory
+* `documents`: The application's Documents directory
+* `cache`: The application's Cache directory
+* `bundle`: The application's bundle; the location of the app itself on disk (read-only)
+* `root`: The entire device filesystem
+
+By default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems, `library-nosync` and `documents-nosync`, which represent a special non-synced directory within the `/Library` or `/Documents` filesystem.
diff --git a/plugins/cordova-plugin-file/RELEASENOTES.md b/plugins/cordova-plugin-file/RELEASENOTES.md
new file mode 100644
index 0000000..063272f
--- /dev/null
+++ b/plugins/cordova-plugin-file/RELEASENOTES.md
@@ -0,0 +1,370 @@
+
+# Release Notes
+
+### 0.2.1 (Sept 5, 2013)
+* [CB-4656] Don't add newlines in data urls within readAsDataUrl.
+* [CB-4514] Making DirectoryCopy Recursive
+* [iOS] Simplify the code in resolveLocalFileSystemURI
+
+### 0.2.3 (Sept 25, 2013)
+* CB-4889 bumping&resetting version
+* [CB-4903] File Plugin not loading Windows8
+* [CB-4903] File Plugin not loading Windows8
+* CB-4889 renaming references
+* CB-4889 renaming org.apache.cordova.core.file to org.apache.cordova.file
+* Rename CHANGELOG.md -> RELEASENOTES.md
+* [CB-4771] Expose TEMPORARY and PERSISTENT constants on window.
+* Fix compiler/lint warnings
+* [CB-4764] Move DirectoryManager.java into file plugin
+* [CB-4763] Copy FileHelper.java into the plugin.
+* [CB-2901] [BlackBerry10] Automatically unsandbox filesystem if path is not in app sandbox
+* [CB-4752] Incremented plugin version on dev branch.
+
+### 0.2.4 (Oct 9, 2013)
+* CB-5020 - File plugin should execute on a separate thread
+* [CB-4915] Incremented plugin version on dev branch.
+* CB-4504: Updating FileUtils.java to compensate for Java porting failures in the Android SDK. This fails because Java knows nothing about android_asset not being an actual filesystem
+
+ ### 0.2.5 (Oct 28, 2013)
+* CB-5129: Add a consistent filesystem attribute to FileEntry and DirectoryEntry objects
+* CB-5128: added repo + issue tag to plugin.xml for file plugin
+* CB-5015 [BlackBerry10] Add missing dependency for File.slice
+* [CB-5010] Incremented plugin version on dev branch.
+
+### 1.0.0 (Feb 05, 2014)
+* CB-5974: Use safe 'Compatibilty' mode by default
+* CB-5915: CB-5916: Reorganize preference code to make defaults possible
+* CB-5974: Android: Don't allow File operations to continue when not configured
+* CB-5960: ios: android: Properly handle parent references in getFile/getDirectory
+* [ubuntu] adopt to recent changes
+* Add default FS root to new FS objects
+* CB-5899: Make DirectoryReader.readEntries return properly formatted Entry objects
+* Add constuctor params to FileUploadResult related to CB-2421
+* Fill out filesystem attribute of entities returned from resolveLocalFileSystemURL
+* CB-5916: Create documents directories if they don't exist
+* CB-5915: Create documents directories if they don't exist
+* CB-5916: Android: Fix unfortunate NPE in config check
+* CB-5916: Android: Add "/files/" to persistent files path
+* CB-5915: ios: Update config preference (and docs) to match issue
+* CB-5916: Android: Add config preference for Android persistent storage location
+* iOS: Add config preference for iOS persistent storage location
+* iOS: Android: Allow third-party plugin registration
+* Android: Expose filePlugin getter so that other plugins can register filesystems
+* Fix typos in deprecation message
+* Add backwards-compatibility shim for file-transfer
+* Android: Allow third-party plugin registration
+* CB-5810 [BlackBerry10] resolve local:/// paths (application assets)
+* CB-5774: create DirectoryEntry instead of FileEntry
+* Initial fix for CB-5747
+* Change default FS URL scheme to "cdvfile"
+* Android: Properly format content urls
+* Android, iOS: Replace "filesystem" protocol string with constant
+* Android: Allow absolute paths on Entry.getFile / Entry.getDirectory
+* Android: Make clear that getFile takes a path, not just a filename
+* CB-5008: Rename resolveLocalFileSystemURI to resolveLocalFileSystemURL; deprecate original
+* Remove old file reference from plugin.xml
+* Android: Refactor File API
+* CB-4899 [BlackBerry10] Fix resolve directories
+* CB-5602 Windows8. Fix File Api mobile spec tests
+* Android: Better support for content urls and cross-filesystem copy/move ops
+* CB-5699 [BlackBerry10] Update resolveLocalFileSystemURI implementation
+* CB-5658 Update license comment formatting of doc/index.md
+* CB-5658 Add doc.index.md for File plugin.
+* CB-5658 Delete stale snapshot of plugin docs
+* CB-5403: Backwards-compatibility with file:// urls where possible
+* CB-5407: Fixes for ContentFilesystem
+* Android: Add method for testing backwards-compatibility of filetransfer plugin
+* iOS: Add method for testing backwards-compatiblity of filetransfer plugin
+* Android: Updates to allow FileTransfer to continue to work
+* Android: Clean up unclosed file objects
+* CB-5407: Cleanup
+* CB-5407: Add new Android source files to plugin.xml
+* CB-5407: Move read, write and truncate methods into modules
+* CB-5407: Move copy/move methods into FS modules
+* CB-5407: Move getParent into FS modules
+* CB-5407: Move getmetadata methods into FS modules
+* CB-5407: Move readdir methods into FS modules
+* CB-5407: Move remove methods into FS modules
+* CB-5407: Move getFile into FS modules
+* CB-5407: Start refactoring android code: Modular filesystems, rfs, rlfsurl
+* CB-5407: Update android JS to use FS urls
+* CB-5405: Use URL formatting for Entry.toURL
+* CB-5532 Fix
+* Log file path for File exceptions.
+* Partial fix for iOS File compatibility with previous fileTransfer plugin
+* CB-5532 WP8. Add binary data support to FileWriter
+* CB-5531 WP8. File Api readAsText incorrectly handles position args
+* Added ubuntu platform support
+* Added amazon-fireos platform support
+* CB-5118 [BlackBerry10] Add check for undefined error handler
+* CB-5406: Extend public API for dependent plugins
+* CB-5403: Bump File plugin major version
+* CB-5406: Split iOS file plugin into modules
+* CB-5406: Factor out filesystem providers in iOS
+* CB-5408: Add handler for filesystem:// urls
+* CB-5406: Update iOS native code to use filesystem URLs internally
+* CB-5405: Update JS code to use URLs exclusively
+* CB-4816 Fix file creation outside sandbox for BB10
+
+### 1.0.1 (Feb 28, 2014)
+* CB-6116 Fix error where resolveLocalFileSystemURL would fail
+* CB-6106 Add support for nativeURL attribute on Entry objects
+* CB-6110 iOS: Fix typo in filesystemPathForURL: method
+* Android: Use most specific FS match when resolving file: URIs
+* iOS: Update fileSystemURLforLocalPath: to return the most match url.
+* Allow third-party plugin registration, and the total count of fs type is not limited to just 4.
+* CB-6097 Added missing files for amazon-fireos platform. Added onLoad flag to true.
+* CB-6087 Android, iOS: Load file plugin on startup
+* CB-6013 BlackBerry10: wrap webkit prefixed called in requestAnimationFrame
+* Update plugin writers' documentation
+* CB-6080 Fix file copy when src and dst are on different local file systems
+* CB-6057 Add methods for plugins to convert between URLs and paths
+* CB-6050 Public method for returning a FileEntry from a device file path
+* CB-2432 CB-3185, CB-5975: Fix Android handling of content:// URLs
+* CB-6022 Add upgrade notes to doc
+* CB-5233 Make asset-library urls work properly on iOS
+* CB-6012 Preserve query strings on cdvfile:// URLs where necessary
+* CB-6010 Test properly for presence of URLforFilesystemPath method
+* CB-5959 Entry.getMetadata should return size attribute
+
+### 1.1.0 (Apr 17, 2014)
+* CB-4965: Remove tests from file plugin
+* Android: Allow file:/ URLs
+* CB-6422: [windows8] use cordova/exec/proxy
+* CB-6249: [android] Opportunistically resolve content urls to file
+* CB-6394: [ios, android] Add extra filesystem roots
+* CB-6394: [ios, android] Fix file resolution for the device root case
+* CB-6394: [ios] Return ENCODING_ERR when fs name is not valid
+* CB-6393: Change behaviour of toURL and toNativeURL
+* ios: Style: plugin initialization
+* ios: Fix handling of file URLs with encoded spaces
+* Always use Android's recommended temp file location for temporary file system
+* CB-6352: Allow FileSystem objects to be serialized to JSON
+* CB-5959: size is explicitly 0 if not set, file.spec.46&47 are testing the type of size
+* CB-6242: [BlackBerry10] Add deprecated version of resolveLocalFileSystemURI
+* CB-6242: [BlackBerry10] add file:/// prefix for toURI / toURL
+* CB-6242: [BlackBerry10] Polyfill window.requestAnimationFrame for OS < 10.2
+* CB-6242: [BlackBerry10] Override window.resolveLocalFileSystemURL
+* CB-6212: [iOS] fix warnings compiled under arm64 64-bit
+* ios: Don't cache responses from CDVFile's URLProtocol
+* CB-6199: [iOS] Fix toNativeURL() not escaping characters properly
+* CB-6148: Fix cross-filesystem copy and move
+* fixed setMetadata() to use the formatted fullPath
+* corrected typo which leads to a "comma expression"
+* CB-4952: ios: Resolve symlinks in file:// URLs
+* Add docs about the extraFileSystems preference
+* CB-6460: Update license headers
+
+### 1.2.0 (Jun 05, 2014)
+* CB-6127 Spanish and French Translations added. Github close #31
+* updated this reference to window
+* Add missing semicolon (copy & paste error)
+* Fix compiler warning about symbol in interface not matching implementation
+* Fix sorting order in supported platforms
+* ubuntu: increase quota value
+* ubuntu: Change FS URL scheme to 'cdvfile'
+* ubuntu: Return size with Entry.getMetadata() method
+* CB-6803 Add license
+* Initial implementation for Firefox OS
+* Small wording tweaks
+* Fixed toURL() toInternalURL() information in the doku
+* ios: Don't fail a write of zero-length payload.
+* CB-285 Docs for cordova.file.\*Directory properties
+* CB-285 Add cordova.file.\*Directory properties for iOS & Android
+* CB-3440 [BlackBerry10] Proxy based implementation
+* Fix typo in docs "app-bundle" -> "bundle"
+* CB-6583 ios: Fix failing to create entry when space in parent path
+* CB-6571 android: Make DirectoryEntry.toURL() have a trailing /
+* CB-6491 add CONTRIBUTING.md
+* CB-6525 android, ios: Allow file: URLs in all APIs. Fixes FileTransfer.download not being called.
+* fix the Windows 8 implementation of the getFile method
+* Update File.js for typo: lastModifiedData --> lastModifiedDate (closes #38)
+* Add error codes.
+* CB-5980 Updated version and RELEASENOTES.md for release 1.0.0
+* Add NOTICE file
+* CB-6114 Updated version and RELEASENOTES.md for release 1.0.1
+* CB-5980 Updated version and RELEASENOTES.md for release 1.0.0
+
+### 1.2.1
+* CB-6922 Fix inconsistent handling of lastModifiedDate and modificationTime
+* CB-285: Document filesystem root properties
+
+### 1.3.0 (Aug 06, 2014)
+* **FFOS** Remove unsupported paths from requestAllPaths
+* **FFOS** Support for resolve URI, request all paths and local app directory.
+* CB-4263 set ready state to done before onload
+* CB-7167 [BlackBerry10] copyTo - return wrapped entry rather than native
+* CB-7167 [BlackBerry10] Add directory support to getFileMetadata
+* CB-7167 [BlackBerry10] Fix tests detection of blob support (window.Blob is BlobConstructor object)
+* CB-7161 [BlackBerry10] Add file system directory paths
+* CB-7093 Create separate plugin.xml for new-style tests
+* CB-7057 Docs update: elaborate on what directories are for
+* CB-7093: Undo the effects of an old bad S&R command
+* CB-7093: Remove a bunch of unneeded log messages
+* CB-7093: Add JS module to plugin.xml file for auto-tests
+* CB-7093 Ported automated file tests
+* **WINDOWS** remove extra function closure, not needed
+* **WINDOWS** remove check for undefined fail(), it is defined by the proxy and always exists
+* **WINDOWS** re-apply readAsBinaryString and readAsArrayBuffer
+* **WINDOWS** Moved similar calls to be the same calls, aliased long namespaced functions
+* CB-6127 Updated translations for docs.
+* CB-6571 Fix getParentForLocalURL to work correctly with directories with trailing '/' (This closes #58)
+* UTTypeCopyPreferredTagWithClass returns nil mimetype for css when there is no network
+* updated spec links in docs ( en only )
+* CB-6571 add trailing space it is missing in DirectoryEnty constructor.
+* CB-6980 Fixing filesystem:null property in Entry
+* Add win8 support for readAsBinaryString and readAsArrayBuffer
+* [FFOS] Update FileProxy.js
+* CB-6940: Fixing up commit from dzeims
+* CB-6940: Android: cleanup try/catch exception handling
+* CB-6940: context.getExternal* methods return null if sdcard isn't in mounted state, causing exceptions that prevent startup from reaching readystate
+* Fix mis-handling of filesystem reference in Entry.moveTo ('this' used in closure).
+* CB-6902: Use File.lastModified rather than .lastModifiedDate
+* CB-6922: Remove unused getMetadata native code
+* CB-6922: Use getFileMetadata consistently to get metadata
+* changed fullPath to self.rootDocsPath
+* CB-6890: Fix pluginManager access for 4.0.x branch
+
+### 1.3.1 (Sep 17, 2014)
+* CB-7471 cordova-plugin-file documentation translation
+* CB-7272 Replace confusing "r/o" abbreviation with just "r"
+* CB-7423 encode path before attempting to resolve
+* CB-7375 Fix the filesystem name in resolveLocalFileSystemUri
+* CB-7445 [BlackBerry10] resolveLocalFileSystemURI - change DEFAULT_SIZE to MAX_SIZE
+* CB-7458 [BlackBerry10] resolveLocalFileSystemURL - add filesystem property
+* CB-7445 [BlackBerry10] Add default file system size to prevent quota exceeded error on initial install
+* CB-7431 Avoid calling done() twice in file.spec.109 test
+* CB-7413 Adds support of 'ms-appdata://' URIs
+* CB-7422 [File Tests] Use proper fileSystem to create fullPath
+* CB-7375 [Entry] get proper filesystem in Entry
+* Amazon related changes.
+* CB-7375 Remove leading slash statement from condition
+* Refactored much of the logic in FileMetadata constructor. Directory.size will return 0
+* CB-7419 [WP8] Added support to get metada from dir
+* CB-7418 [DirectoryEntry] Added fullPath variable as part of condition
+* CB-7417 [File tests] added proper matcher to compare fullPath property
+* CB-7375 Partial revert to resolve WP8 failures
+* Overwrite existing file on getFile when create is true
+* CB-7375 CB-6148: Ensure that return values from copy and move operations reference the correct filesystem
+* CB-6724 changed style detail on documentation
+* Added new js files to amazon-fireos platform.
+* Adds Windows platform
+* Fixes multiple mobilespec tests errors
+* Removed test/tests.js module from main plugin.xml
+* CB-7094 renamed folder to tests + added nested plugin.xml
+* added documentation for manual tests
+* CB-6923 Adding support to handle relative paths
+* Style improvements on Manual tests
+* CB-7094 Ported File manual tests
+
+### 1.3.2 (Dec 02, 2014)
+* Gets rid of thread block error in File plugin
+* CB-7917 Made tests file.spec.114 - 116 pass for **Windows** platform
+* CB-7977 Mention `deviceready` in plugin docs
+* CB-7602: Fix `isCopyOnItself` logic
+* CB-7700 cordova-plugin-file documentation translation: cordova-plugin-file
+* Use one proxy for both **Windows** and **Windows8** platforms
+* CB-6994 Fixes result, returned by proxy's write method
+* [fxos] update `__format__` to match `pathsPrefix`
+* CB-6994 Improves merged code to be able to write a File
+* Optimize `FileProxy` for **Windows** platforms
+* Synchronize changes with **Windows** platform
+* Fix function write for big files on **Windows 8**
+* Write file in background
+* CB-7487 **Android** Broadcast file write This allows MTP USB shares to show the file immediately without reboot/manual refresh using 3rd party app.
+* CB-7700 cordova-plugin-file documentation translation: cordova-plugin-file
+* CB-7571 Bump version of nested plugin to match parent plugin
+
+### 1.3.3 (Feb 04, 2015)
+* CB-7927 Encoding data to bytes instead of chars when writing a file.
+* ios: Fix compile warning about implicit int conversion
+* CB-8351 ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension
+* CB-8351 ios: Use argumentForIndex rather than NSArray extension
+* CB-8351 ios: Use a local copy of valueForKeyIsNumber rather than CordovaLib's version
+* windows: Handle url's containing absolute windows path starting with drive letter and colon (encoded as %3A) through root FS
+* windows: Rework to use normal url form
+* android: refactor: Make Filesystem base class store its own name, rootUri, and rootEntry
+* android: Simplify code a bit by making makeEntryForPath not throw JSONException
+* CB-6431 android: Fix plugin breaking content: URLs
+* CB-7375 Never create new FileSystem instances (except on windows since they don't implement requestAllFileSystems())
+
+### 2.0.0 (Apr 15, 2015)
+* CB-8849 Fixed ReadAsArrayBuffer to return ArrayBuffer and not Array on WP8
+* CB-8819 Fixed FileReader's readAsBinaryString on wp8
+* CB-8746 gave plugin major version bump
+* CB-8683 android: Fix broken unit tests from plugin rename
+* 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
+* docs: added Windows to supported platforms
+* CB-8699 CB-6428 Fix uncompressed assets being copied as zero length files
+* CB-6428 android: Fix assets FileEntry having size of -1
+* android: Move URLforFullPath into base class (and rename to localUrlforFullPath)
+* CB-6428 Mention build-extras.gradle in README
+* CB-7109 android: Parse arguments off of the main thread (close #97)
+* CB-8695 ios: Fix `blob.slice()` for `asset-library` URLs (close #105)
+* Tweak build-extras.gradle to just read/write to main `assets/` instead of `build/`
+* CB-8689 Fix NPE in makeEntryForNativeUri (was affecting file-transfer)
+* CB-8675 Revert "CB-8351 ios: Use base64EncodedStringWithOptions instead of CordovaLib's class extension"
+* CB-8653 Updated Readme
+* CB-8659: ios: 4.0.x Compatibility: Remove use of initWebView method
+* Add a cache to speed up AssetFilesystem directory listings
+* CB-8663 android: Don't notify MediaScanner of private files
+* Don't log stacktrace for normal exceptions (e.g. file not found)
+* android: Don't use LimitedInputStream when reading entire file (optimization)
+* CB-6428 android: Add support for directory copies from assets -> filesystem
+* android: Add `listChildren()`: Java-consumable version of `readEntriesAtLocalURL()`
+* CB-6428 android: Add support for file:///android_asset URLs
+* CB-8642 android: Fix content URIs not working with resolve / copy
+* Tweak tests to fail if deleteEntry fails (rather than time out)
+* android: Ensure LocalFilesystemURL can only be created with "cdvfile" URLs
+* android: Move CordovaResourceApi into Filesystem base class
+* android: Use `CordovaResourceApi.mapUriToFile()` rather than own custom logic in ContentFilesystem
+* android: Use Uri.parse rather than manual parsing in resolveLocalFileSystemURI
+* Tweak test case that failed twice on error rather than just once
+* android: Delete invalid JavaDoc (lint errors)
+* android: Use CordovaResourceApi rather than FileHelper
+* CB-8032 - File Plugin - Add nativeURL external method support for CDVFileSystem->makeEntryForPath:isDirectory: (closes #96)
+* CB-8567 Integrate TravisCI
+* CB-8438 cordova-plugin-file documentation translation: cordova-plugin-file
+* CB-8538 Added package.json file
+* CB-7956 Add cordova-plugin-file support for browser platform
+* CB-8423 Corrected usage of done() in async tests
+* CB-8459 Fixes spec 111 failure due to incorrect relative paths handling
+* Code cleanup, whitespace
+* Added nativeURL property to FileEntry, implemented readAsArrayBuffer and readAsBinaryString
+
+### 2.1.0 (Jun 17, 2015)
+* added missing license header
+* CB-9128 cordova-plugin-file documentation translation: cordova-plugin-file
+* fix npm md
+* CB-8844 Increased timeout for asset tests
+* Updated resolveFileSystem.js so it can be parsed by uglifyJS
+* CB-8860 cordova-plugin-file documentation translation: cordova-plugin-file
+* CB-8792 Fixes reading of json files using readAsText
+
+### 3.0.0 (Aug 18, 2015)
+* Make Android default persistent file location internal
+* Fixed issue with file paths not existing when using browserify
+* CB-9251: Changed from Intents to Preferences object as per the issue
+* CB-9215 Add cordova-plugin-file manual test for windows platform
diff --git a/plugins/cordova-plugin-file/doc/de/README.md b/plugins/cordova-plugin-file/doc/de/README.md
new file mode 100644
index 0000000..242a2f7
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/de/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+Dieses Plugin implementiert eine File-API, die Lese-/Schreibzugriff Zugriff auf Dateien, die auf dem Gerät befinden.
+
+Dieses Plugin basiert auf mehrere Angaben, einschließlich: die HTML5-File-API
+
+Die (heute nicht mehr existierenden) Verzeichnisse und System neuesten Erweiterungen: , obwohl die meisten von den Plugin-Code wurde geschrieben, als eine frühere Spec aktuell waren:
+
+Es implementiert auch die FileWriter Spec:
+
+Verwendung finden Sie in HTML5 Rocks ausgezeichnete [Dateisystem Artikel.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+Finden Sie einen Überblick über andere Speicheroptionen Cordovas [Speicher-Führer](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+Dieses Plugin wird global `cordova.file`-Objekt definiert.
+
+Obwohl im globalen Gültigkeitsbereich, steht es nicht bis nach dem `deviceready`-Ereignis.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Installation
+
+ cordova plugin add cordova-plugin-file
+
+
+## Unterstützte Plattformen
+
+ * Amazon Fire OS
+ * Android
+ * BlackBerry 10
+ * Firefox OS
+ * iOS
+ * Windows Phone 7 und 8 *
+ * Windows 8 *
+ * Windows*
+ * Browser
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## Wo Dateien gespeichert
+
+Stand: V1 werden URLs auf wichtige Datei-System-Verzeichnisse zur Verfügung gestellt. Jede URL in der Form *file:///path/to/spot/* ist, und ein `DirectoryEntry` mit `window.resolveLocalFileSystemURL()` konvertiert werden können.
+
+ * `cordova.file.applicationDirectory`-Die schreibgeschützten Verzeichnis, in dem die Anwendung installiert ist. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.applicationStorageDirectory`-Root-Verzeichnis der Anwendungs-Sandbox; auf iOS ist schreibgeschützt (aber bestimmte Unterverzeichnisse [wie `/Documents` ] sind Lese-und Schreibzugriff). Alle enthaltene Daten ist für die app privat. ( *iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.dataDirectory`-Beständige und private Datenspeicherung innerhalb der Anwendungs-Sandbox, die mit internen Speicher (auf Android, externen Speicher verwenden, verwenden Sie `.externalDataDirectory` ). Auf iOS, ist dieses Verzeichnis nicht mit iCloud synchronisiert (verwenden Sie `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.cacheDirectory`-Verzeichnis der zwischengespeicherten Daten-Dateien oder Dateien, die Ihre app einfach neu erstellen können. Das Betriebssystem kann diese Dateien löschen, wenn das Gerät auf Speicher knapp wird, dennoch sollten die apps vom Betriebssystem zum Löschen von Dateien hier nicht verlassen. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-Anwendungsraum auf externen Speicher. (*Android*)
+
+ * `cordova.file.externalDataDirectory`-Wo, app-spezifische Datendateien auf externen Speicher setzen. (*Android*)
+
+ * `cordova.file.externalCacheDirectory`-Anwendungscache auf externen Speicher. (*Android*)
+
+ * `cordova.file.externalRootDirectory`-Externer Speicher (SD-Karte) Stamm. (*Android*, *BlackBerry 10*)
+
+ * `cordova.file.tempDirectory`-Temp-Verzeichnis, dem das OS auf deaktivieren können wird. Verlassen Sie sich nicht auf das Betriebssystem, um dieses Verzeichnis zu löschen; Ihre Anwendung sollte immer Dateien gegebenenfalls entfernen. (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-Hält app-spezifische Dateien, die (z. B. auf iCloud) synchronisiert werden sollten. (*iOS*)
+
+ * `cordova.file.documentsDirectory`-Dateien für die app, aber privat sind sinnvoll, andere Anwendungen (z.B. Office-Dateien). (*iOS*)
+
+ * `cordova.file.sharedDirectory`-Dateien für alle Anwendungen (*BlackBerry 10* weltweit verfügbar)
+
+## Dateisystemlayouts
+
+Obwohl technisch ein Implementierungsdetail, kann es sehr hilfreich zu wissen, wie die `cordova.file.*`-Eigenschaften physikalische Pfade auf einem echten Gerät zugeordnet sein.
+
+### iOS-Datei-System-Layout
+
+| Gerätepfad | `Cordova.file.*` | `iosExtraFileSystems` | R/w? | persistent? | OS löscht | Sync | Private |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-----------:|:------------:|:----:|:-------:|
+| `/ Var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Ja |
+| `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Ja |
+| `www/` | - | - | r | N/A | N/A | N/A | Ja |
+| `Documents/` | documentsDirectory | Dokumente | R/w | Ja | Nein | Ja | Ja |
+| `NoCloud/` | - | Dokumente-nosync | R/w | Ja | Nein | Nein | Ja |
+| `Library` | - | Bibliothek | R/w | Ja | Nein | Ja? | Ja |
+| `NoCloud/` | dataDirectory | Bibliothek-nosync | R/w | Ja | Nein | Nein | Ja |
+| `Cloud/` | syncedDataDirectory | - | R/w | Ja | Nein | Ja | Ja |
+| `Caches/` | cacheDirectory | Cache | R/w | Ja * | Ja**\* | Nein | Ja |
+| `tmp/` | tempDirectory | - | R/w | Nein** | Ja**\* | Nein | Ja |
+
+\ * Dateien über app-Neustarts und Upgrades beibehalten, aber dieses Verzeichnis kann gelöscht werden, wenn das OS begehrt. Ihre Anwendung sollte in der Lage, alle Inhalte neu zu erstellen, die gelöscht werden können.
+
+** -Dateien kann über app-Neustarts beizubehalten, aber verlasse dich nicht auf dieses Verhalten. Dateien sind nicht unbedingt Aktuelles beibehalten. Ihre Anwendung sollte Dateien aus diesem Verzeichnis entfernen, wenn es gilt, diese Dateien werden entfernt, da das OS nicht wann (oder auch wenn) garantiert.
+
+**\ * The OS kann den Inhalt dieses Verzeichnisses löschen, wann immer es sich anfühlt, ist es erforderlich, aber verlassen Sie sich nicht dazu. Sie sollten dieses Verzeichnis entsprechend Ihrer Anwendung deaktivieren.
+
+### Android File System-Layout
+
+| Gerätepfad | `Cordova.file.*` | `AndroidExtraFileSystems` | R/w? | persistent? | OS löscht | Private |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:-----------:|:----------:|:-------:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Ja |
+| `/ Data/Data/< app-Id > /` | applicationStorageDirectory | - | R/w | N/A | N/A | Ja |
+| `cache` | cacheDirectory | Cache | R/w | Ja | Ja\* | Ja |
+| `files` | dataDirectory | Dateien | R/w | Ja | Nein | Ja |
+| `Documents` | | Dokumente | R/w | Ja | Nein | Ja |
+| `< Sdcard > /` | externalRootDirectory | sdcard | R/w | Ja | Nein | Nein |
+| `Android/data//` | externalApplicationStorageDirectory | - | R/w | Ja | Nein | Nein |
+| `cache` | externalCacheDirectry | Cache-extern | R/w | Ja | Nein** | Nein |
+| `files` | externalDataDirectory | Dateien-extern | R/w | Ja | Nein | Nein |
+
+\ * OS kann regelmäßig dieses Verzeichnis zu löschen, aber verlasse dich nicht auf dieses Verhalten. Deaktivieren Sie den Inhalt dieses Verzeichnisses für Ihre Anwendung geeigneten. Ein Benutzer den Cache manuell löschen sollte, werden die Inhalte dieses Verzeichnisses entfernt.
+
+** Der OS nicht klar dieses Verzeichnis automatisch; Sie sind verantwortlich für die Inhalte selbst verwalten. Der Benutzer den Cache manuell löschen sollte, werden der Inhalt des Verzeichnisses entfernt.
+
+**Hinweis**: Wenn externe Speichergeräte nicht bereitgestellt werden kann, sind die `cordova.file.external*` Eigenschaften `null`.
+
+### BlackBerry 10-File-System-Layout
+
+| Gerätepfad | `Cordova.file.*` | R/w? | persistent? | OS löscht | Private |
+|:----------------------------------------------------------- |:--------------------------- |:----:|:-----------:|:---------:|:-------:|
+| `file:///Accounts/1000/APPDATA/ < app Id > /` | applicationStorageDirectory | r | N/A | N/A | Ja |
+| `app/native` | applicationDirectory | r | N/A | N/A | Ja |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | R/w | Nein | Ja | Ja |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | R/w | Ja | Nein | Ja |
+| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | R/w | Ja | Nein | Nein |
+| `file:///Accounts/1000/Shared` | sharedDirectory | R/w | Ja | Nein | Nein |
+
+*Hinweis*: Wenn die Anwendung bereitgestellt wird, um Perimeter zu arbeiten, alle Pfade sind relativ /accounts/1000-enterprise.
+
+## Android Eigenarten
+
+### Android permanenten Speicherort
+
+Es gibt mehrere gültige Speicherorte, persistente Dateien auf einem Android-Gerät zu speichern. Finden Sie auf [dieser Seite](http://developer.android.com/guide/topics/data/data-storage.html) eine ausführliche Diskussion über die verschiedenen Möglichkeiten.
+
+Frühere Versionen des Plugins wählen würde, den Speicherort der temporären und permanenten Dateien beim Start, basierend auf, ob das Gerät behauptete, dass die SD-Karte (oder gleichwertige Speicherpartition) bereitgestellt wurde. Wenn die SD-Karte eingelegt wurde, oder wenn eine große interne Speicherpartition verfügbar war (wie auf Nexus-Geräten) und dann in die Wurzel dieses Raumes, die persistenten Dateien gespeichert werden. Dies bedeutete, dass alle Cordova apps aller verfügbaren Dateien auf der Karte sehen konnte.
+
+Wenn die SD-Karte nicht verfügbar war, dann Vorgängerversionen Daten unter speichern würde `/data/data/`, die isoliert Anwendungen voneinander, aber möglicherweise noch Ursache Daten zwischen Benutzern freigegeben werden.
+
+Es ist jetzt möglich, ob Sie Dateien der internen Datei-Speicherort oder unter Verwendung der bisherigen Logik, mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
+
+
+
+
+
+
+Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
+
+Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Wechseln die Location auf "Internal" würde bedeuten, dass Benutzer, die aktualisieren Sie ihre Anwendung, möglicherweise nicht auf ihre zuvor gespeicherte Dateien, abhängig von ihrem Gerät zugreifen.
+
+Wenn Ihre Anwendung neu ist, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die `Internal` Einstellung in der Regel empfohlen.
+
+### Langsame rekursive Operationen für /android_asset
+
+Auflisten von Verzeichnissen Vermögenswert ist wirklich langsam auf Android. Sie können beschleunigen, es oben aber durch `src/android/build-extras.gradle` in das Stammverzeichnis von Ihrem android Projekt hinzufügen (erfordert auch cordova-android@4.0.0 oder größer).
+
+## iOS Macken
+
+ * `cordova.file.applicationStorageDirectory`ist schreibgeschützt; zum Speichern von Dateien im Stammverzeichnis der Versuch schlägt fehl. Verwenden Sie eine der anderen `cordova.file.*` für iOS definierten Eigenschaften (nur `applicationDirectory` und `applicationStorageDirectory` sind schreibgeschützt).
+ * `FileReader.readAsText(blob, encoding)`
+ * Die `encoding` Parameter wird nicht unterstützt und UTF-8-Kodierung ist immer wirksam.
+
+### iOS permanenten Speicherort
+
+Es gibt zwei gültige Speicherorte persistente Dateien auf ein iOS-Gerät speichern: das Dokumenten-Verzeichnis und das Verzeichnis Library. Frühere Versionen des Plugins gespeichert immer nur persistente Dateien im Verzeichnis Dokumente. Dies hatte den Nebeneffekt einer Anwendung Dateien in iTunes, die oft unbeabsichtigte, speziell für Anwendungen, die viele kleine Dateien behandeln war, sichtbar zu machen, anstatt komplette Dokumente für den Export, die den beabsichtigten Zweck des Verzeichnisses ist zu produzieren.
+
+Es ist jetzt möglich, ob Sie Dateien in Dokumente oder Verzeichnis Library mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
+
+
+
+
+
+
+Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
+
+Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Standort zur `Library` wechseln würde bedeuten, dass Benutzer, die ihre Anwendung aktualisieren nicht in der Lage wäre, ihre zuvor gespeicherte Dateien zugreifen.
+
+Wenn die Anwendung neu, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die Einstellung der `Library` allgemein empfohlen.
+
+## Firefox OS Macken
+
+Der Datei-System-API wird von Firefox-OS nicht nativ unterstützt und wird als ein Shim auf IndexedDB implementiert.
+
+ * Schlägt nicht fehl, wenn Sie nicht leere Verzeichnisse entfernen
+ * Metadaten wird für Verzeichnisse nicht unterstützt.
+ * Methoden `copyTo` und `moveTo` unterstützen keine Verzeichnisse
+
+Die folgenden Datenpfade werden unterstützt: * `applicationDirectory` - `xhr` verwendet, um lokale Dateien erhalten, die mit der app verpackt sind. *`dataDirectory` - für persistente app-spezifische Daten-Dateien. *`cacheDirectory` - Cache-Dateien, die app startet überleben sollte (Apps sollten nicht vom Betriebssystem zum Löschen von Dateien hier verlassen).
+
+## Browser-Eigenheiten
+
+### Gemeinsamen Macken und Bemerkungen
+
+ * Jeder Browser verwendet ein eigene Sandbox Dateisystem. IE und Firefox verwenden IndexedDB als Basis. Alle Browser verwenden Schrägstrich als Verzeichnistrennzeichen in einem Pfad.
+ * Directory-Einträge müssen nacheinander erstellt werden. Z. B. der Aufruf `fs.root.getDirectory ("dir1/Ordner2 ', {create:true}, SuccessCallback, ErrorCallback)` schlägt fehl, wenn dir1 nicht existierte.
+ * Das Plugin fordert Benutzer die Berechtigung zum permanenten Speicher beim ersten Start Anwendung verwenden.
+ * Plugin unterstützt `Cdvfile://localhost` (lokale Ressourcen) nur. D.h. externe Ressourcen nicht über `Cdvfile` unterstützt.
+ * Das Plugin folgt nicht ["File System API 8.3 Naming Einschränkungen"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
+ * BLOB und Datei "`close`-Funktion wird nicht unterstützt.
+ * `FileSaver` und `BlobBuilder` werden von diesem Plugin nicht unterstützt und müssen nicht geboren.
+ * Das Plugin unterstützt keine `RequestAllFileSystems`. Diese Funktion fehlt auch in den Spezifikationen.
+ * Einträge im Verzeichnis werden nicht entfernt werden, wenn Sie verwenden `create: true` Flag für vorhandenes Verzeichnis.
+ * Über Konstruktor erstellte Dateien werden nicht unterstützt. Sie sollten stattdessen die entry.file-Methode verwenden.
+ * Jeder Browser verwendet eine eigene Form für Blob-URL-Verweise.
+ * `readAsDataURL`-Funktion wird unterstützt, aber die Mediatype in Chrom hängt von der Eintrag Namenerweiterung, Mediatype im IE immer leer ist (das ist dasselbe wie `Text-Plain` gemäß der Spezifikation), Mediatype in Firefox ist immer `Application/Octet-Stream`. Beispielsweise, wenn der Inhalt `Abcdefg` gibt dann Firefox `Daten: Anwendung / Octet-Stream; base64, YWJjZGVmZw ==`, IE gibt `Daten:; base64, YWJjZGVmZw ==`, Chrom gibt `Daten: < Mediatype je nach Erweiterung des Eintragsnamens >; base64, YWJjZGVmZw ==`.
+ * `ToInternalURL` gibt den Pfad zurück, in der Form `file:///persistent/path/to/entry` (Firefox, IE). Chrom gibt den Pfad zurück, in der Form `cdvfile://localhost/persistent/file`.
+
+### Chrom-Macken
+
+ * Chrom-Dateisystem ist nicht sofort nach Gerät bereit. Als Workaround können Sie `FilePluginIsReady`-Ereignis abonnieren. Beispiel:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+`Window.isFilePluginReadyRaised`-Funktion können Sie überprüfen, ob Ereignis bereits ausgelöst wurde. -window.requestFileSystem temporär und PERSISTENTE Dateisystem-Quoten sind nicht begrenzt, in Chrom. -Um die dauerhafte Speicherung in Chrom zu erhöhen benötigen Sie `window.initPersistentFileSystem`-Methode aufrufen. Permanenter Speicherkontingent beträgt 5 MB standardmäßig. -Chrome erforderlich `--erlauben-Datei-Zugriff-aus-Files` Argument an den Support API via `file:///` Protokoll führen. -`Datei`-Objekt wird nicht geändert werden, wenn Sie Flag verwenden `{create:true}` als einen vorhandenen `Eintrag` zu erhalten. -Veranstaltungen `cancelable`-Eigenschaft festgelegt ist in Chrom wahr. Dies widerspricht der [Spezifikation](http://dev.w3.org/2009/dap/file-system/file-writer.html). -`toURL`-Funktion in Chrome zurück `Dateisystem:`-Pfad je nach Anwendungshost vorangestellt. Z. B. `filesystem:file:///persistent/somefile.txt`, `Filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` Funktionsergebnis enthält keine nachgestellten Schrägstrich bei Verzeichniseintrag. Chrom löst Verzeichnisse mit Schrägstrich-gezogene Urls aber korrekt. -`ResolveLocalFileSystemURL`-Methode erfordert die eingehenden `Url` `Dateisystem` Präfix haben. Beispielsweise sollte die `Url`-Parameter für `ResolveLocalFileSystemURL` in der Form `filesystem:file:///persistent/somefile.txt` im Gegensatz zu der Form `file:///persistent/somefile.txt` in Android. -Veraltete `ToNativeURL`-Funktion wird nicht unterstützt und muss keinen Stub. -`SetMetadata`-Funktion ist nicht in den Spezifikationen angegeben und nicht unterstützt. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, statt SYNTAX_ERR(code: 8) auf anfordern des Dateisystems nicht existent. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt PATH_EXISTS_ERR(code: 12) zu versuchen, die ausschließlich eine Datei oder ein Verzeichnis zu erstellen, die bereits vorhanden ist. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NO_MODIFICATION_ALLOWED_ERR(code: 6) zu versuchen, rufen Sie RemoveRecursively auf das Root-Dateisystem. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NOT_FOUND_ERR(code: 1) zu versuchen, MoveTo-Verzeichnis, das nicht vorhanden ist.
+
+### Auf der Grundlage von IndexedDB Impl Macken (Firefox und IE)
+
+ * `.` und `.` werden nicht unterstützt.
+ * IE unterstützt keine `file:///`-Modus; nur der Modus für gehostete ist unterstützten (Http://localhost:xxxx).
+ * Firefox Dateisystem Größe ist nicht begrenzt, aber jede 50MB-Erweiterung wird eine Benutzer die Berechtigung anzufordern. IE10 können bis zu 10mb kombinierte AppCache und IndexedDB in Implementierung des Dateisystems verwendet, ohne Aufforderung, sobald Sie dieses Niveau, werden, das Sie aufgefordert werden schlagen, wenn Sie es bis Max 250 mb pro Standort erhöht werden sollen. `Size`-Parameter für `RequestFileSystem` Funktion wirkt also nicht Dateisystem in Firefox und IE.
+ * `ReadAsBinaryString` Funktion heißt es nicht in die Angaben und in IE nicht unterstützt und muss keinen Stub.
+ * `file.Type` ist immer null.
+ * Sie sollten nicht erstellen Eintrag mit DirectoryEntry Instanz Rückrufergebnis, die gelöscht wurde. Andernfalls erhalten Sie einen "hängende Eintrag".
+ * Bevor Sie eine Datei lesen können, die gerade geschrieben wurde, müssen Sie eine neue Instanz dieser Datei erhalten.
+ * `SetMetadata`-Funktion, die nicht in den Specs genannt unterstützt Feldänderung nur `ModificationTime`.
+ * `CopyTo` und `MoveTo`-Funktionen unterstützen keine Verzeichnisse.
+ * Verzeichnisse-Metadaten werden nicht unterstützt.
+ * Beide Entry.remove und directoryEntry.removeRecursively nicht scheitern, wenn nicht leere Verzeichnisse entfernen - Verzeichnisse entfernt werden stattdessen zusammen mit Inhalt gereinigt.
+ * `abort` und `truncate`-Funktionen werden nicht unterstützt.
+ * Progress-Ereignisse werden nicht ausgelöst. Beispielsweise wird dieser Handler nicht ausgeführt werden:
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## Upgrade Notes
+
+In v1.0.0 dieses Plugins haben die `FileEntry` und `DirectoryEntry` Strukturen geändert, um mehr im Einklang mit der veröffentlichten Spezifikation sein.
+
+Vorgängerversionen (Pre-1.0.0) des Plugins den Gerät-Absolute-Dateispeicherort in der Eigenschaft `fullPath` `Entry` Objekte gespeichert. Diese Pfade würde in der Regel aussehen
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Diese Pfade wurden auch von der `toURL()`-Methode der `Entry` Objekte zurückgegeben.
+
+Mit v1.0.0 ist das `fullPath`-Attribut den Pfad zu der Datei, *relativ zum Stammverzeichnis des Dateisystems HTML*. Also, würde die oben genannten Wege jetzt beide durch ein `FileEntry`-Objekt mit einem `fullPath` von dargestellt werden
+
+ /path/to/file
+
+
+Wenn Ihre Anwendung mit absoluter Gerätepfade arbeitet und Sie zuvor diese Pfade durch die Eigenschaft `fullPath` `Entry` Objekte abgerufen, sollten dann Sie den Code, um stattdessen `entry.toURL()` verwenden aktualisieren.
+
+Für rückwärts Kompatibilität, die `resolveLocalFileSystemURL()`-Methode wird einen Absolute-Gerätepfad zu akzeptieren und kehrt ein `Entry`-Objekt entspricht, solange diese Datei in den `TEMPORARY` oder `PERSISTENT` Dateisysteme existiert.
+
+Dies wurde vor allem ein Problem mit dem File-Transfer-Plugin, die zuvor-Absolute-Gerätepfade verwendet (und kann damit noch einverstanden). Es wurde überarbeitet, um mit Dateisystem-URLs korrekt zu arbeiten, damit ersetzen `entry.fullPath` mit `entry.toURL()` immer das Plugin zum Arbeiten mit Dateien auf dem Gerät Probleme lösen sollte.
+
+In v1.1.0 wurde der Rückgabewert von `toURL()` (siehe \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) geändert, um eine absolute "file://" URL zurückgeben. wo immer möglich. Sicherstellung einer ' Cdvfile:'-URL können Sie an `toInternalURL()`. Diese Methode gibt jetzt Dateisystem URLs der Form zurück.
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+die benutzt werden können, um die Datei eindeutig zu identifizieren.
+
+## Liste der Fehlercodes und Bedeutungen
+
+Wenn ein Fehler ausgelöst wird, wird eines der folgenden Codes verwendet werden.
+
+| Code | Konstante |
+| ----:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Konfigurieren das Plugin (Optional)
+
+Die Menge der verfügbaren Dateisysteme kann pro Plattform konfiguriert sein. Erkennen von iOS und Android ein Tag in `"config.xml"` die Namen der Dateisysteme installiert werden. Standardmäßig sind alle Datei-System-Roots aktiviert.
+
+
+
+
+
+### Android
+
+ * `files`: interne Datei-Speicher-Verzeichnis der Anwendung
+ * `files-external`: Verzeichnis der Anwendung externe Datei Speicher
+ * `sdcard`: das externe Globaldatei-Speicherverzeichnis (Dies ist die Wurzel der SD-Karte, sofern installiert). Sie benötigen die Berechtigung zur Verwendung dieses `android.permission.WRITE_EXTERNAL_STORAGE`.
+ * `cache`: internen Cache-Verzeichnis der Anwendung
+ * `cache-external`: externer Cache-Verzeichnis der Anwendung
+ * `root`: das gesamte Gerät-Dateisystem
+
+Android unterstützt auch eine spezielle Dateisystem mit dem Namen "documents", die ein Unterverzeichnis "/Documents/" die "files" Dateisystem darstellt.
+
+### iOS
+
+ * `library`: Bibliothek-Verzeichnis der Anwendung
+ * `documents`: Dokumente-Verzeichnis der Anwendung
+ * `cache`: Cache-Verzeichnis der Anwendung
+ * `bundle`: die Anwendung Bündel; den Speicherort der die app selbst auf dem Datenträger (schreibgeschützt)
+ * `root`: das gesamte Gerät-Dateisystem
+
+Standardmäßig können die Bibliothek und Dokumenten-Verzeichnisse mit iCloud synchronisiert werden. Sie können auch verlangen, zwei zusätzliche Dateisysteme, `library-nosync` und `documents-nosync`, die einem speziellen nicht synchronisierten Verzeichnis innerhalb darstellen der `/Library` oder `/Documents`-Dateisystem.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/de/index.md b/plugins/cordova-plugin-file/doc/de/index.md
new file mode 100644
index 0000000..2a51695
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/de/index.md
@@ -0,0 +1,338 @@
+
+
+# cordova-plugin-file
+
+Dieses Plugin implementiert eine File-API, die Lese-/Schreibzugriff Zugriff auf Dateien, die auf dem Gerät befinden.
+
+Dieses Plugin basiert auf mehrere Angaben, einschließlich: die HTML5-File-API
+
+Die (heute nicht mehr existierenden) Verzeichnisse und System neuesten Erweiterungen: , obwohl die meisten von den Plugin-Code wurde geschrieben, als eine frühere Spec aktuell waren:
+
+Es implementiert auch die FileWriter Spec:
+
+Verwendung finden Sie in HTML5 Rocks ausgezeichnete [Dateisystem Artikel.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+Finden Sie einen Überblick über andere Speicheroptionen Cordovas [Speicher-Führer][2].
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+Dieses Plugin wird global `cordova.file`-Objekt definiert.
+
+Obwohl im globalen Gültigkeitsbereich, steht es nicht bis nach dem `deviceready`-Ereignis.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Installation
+
+ cordova plugin add cordova-plugin-file
+
+
+## Unterstützte Plattformen
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Firefox OS
+* iOS
+* Windows Phone 7 und 8 *
+* Windows 8 *
+* Browser
+
+* *Diese Plattformen unterstützen nicht `FileReader.readAsArrayBuffer` noch `FileWriter.write(blob)`.*
+
+## Wo Dateien gespeichert
+
+Stand: V1 werden URLs auf wichtige Datei-System-Verzeichnisse zur Verfügung gestellt. Jede URL in der Form *file:///path/to/spot/* ist, und ein `DirectoryEntry` mit `window.resolveLocalFileSystemURL()` konvertiert werden können.
+
+* `cordova.file.applicationDirectory`-Die schreibgeschützten Verzeichnis, in dem die Anwendung installiert ist. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.applicationStorageDirectory`-Root-Verzeichnis der Anwendungs-Sandbox; auf iOS ist schreibgeschützt (aber bestimmte Unterverzeichnisse [wie `/Documents` ] sind Lese-und Schreibzugriff). Alle enthaltene Daten ist für die app privat. ( *iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.dataDirectory`-Beständige und private Datenspeicherung innerhalb der Anwendungs-Sandbox, die mit internen Speicher (auf Android, externen Speicher verwenden, verwenden Sie `.externalDataDirectory` ). Auf iOS, ist dieses Verzeichnis nicht mit iCloud synchronisiert (verwenden Sie `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.cacheDirectory`-Verzeichnis der zwischengespeicherten Daten-Dateien oder Dateien, die Ihre app einfach neu erstellen können. Das Betriebssystem kann diese Dateien löschen, wenn das Gerät auf Speicher knapp wird, dennoch sollten die apps vom Betriebssystem zum Löschen von Dateien hier nicht verlassen. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-Anwendungsraum auf externen Speicher. (*Android*)
+
+* `cordova.file.externalDataDirectory`-Wo, app-spezifische Datendateien auf externen Speicher setzen. (*Android*)
+
+* `cordova.file.externalCacheDirectory`-Anwendungscache auf externen Speicher. (*Android*)
+
+* `cordova.file.externalRootDirectory`-Externer Speicher (SD-Karte) Stamm. (*Android*, *BlackBerry 10*)
+
+* `cordova.file.tempDirectory`-Temp-Verzeichnis, dem das OS auf deaktivieren können wird. Verlassen Sie sich nicht auf das Betriebssystem, um dieses Verzeichnis zu löschen; Ihre Anwendung sollte immer Dateien gegebenenfalls entfernen. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-Hält app-spezifische Dateien, die (z. B. auf iCloud) synchronisiert werden sollten. (*iOS*)
+
+* `cordova.file.documentsDirectory`-Dateien für die app, aber privat sind sinnvoll, andere Anwendungen (z.B. Office-Dateien). (*iOS*)
+
+* `cordova.file.sharedDirectory`-Dateien für alle Anwendungen (*BlackBerry 10* weltweit verfügbar)
+
+## Dateisystemlayouts
+
+Obwohl technisch ein Implementierungsdetail, kann es sehr hilfreich zu wissen, wie die `cordova.file.*`-Eigenschaften physikalische Pfade auf einem echten Gerät zugeordnet sein.
+
+### iOS-Datei-System-Layout
+
+| Gerätepfad | `Cordova.file.*` | `iosExtraFileSystems` | R/w? | persistent? | OS löscht | Sync | Private |
+|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-----------:|:----------:|:----:|:-------:|
+| `/ Var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Ja |
+| `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Ja |
+| `www/` | - | - | r | N/A | N/A | N/A | Ja |
+| `Documents/` | documentsDirectory | Dokumente | R/w | Ja | Nein | Ja | Ja |
+| `NoCloud/` | - | Dokumente-nosync | R/w | Ja | Nein | Nein | Ja |
+| `Library` | - | Bibliothek | R/w | Ja | Nein | Ja? | Ja |
+| `NoCloud/` | dataDirectory | Bibliothek-nosync | R/w | Ja | Nein | Nein | Ja |
+| `Cloud/` | syncedDataDirectory | - | R/w | Ja | Nein | Ja | Ja |
+| `Caches/` | cacheDirectory | Cache | R/w | Ja * | Ja * * *| | Nein | Ja |
+| `tmp/` | tempDirectory | - | R/w | Nicht * * | Ja * * *| | Nein | Ja |
+
+* Dateien werden hinweg app Neustarts und Upgrades beibehalten, aber dieses Verzeichnis kann gelöscht werden, wenn das OS begehrt. Ihre Anwendung sollte in der Lage, Inhalte zu erschaffen, die möglicherweise gelöscht werden.
+
+* *-Dateien kann über app-Neustarts beizubehalten, aber verlasse dich nicht auf dieses Verhalten. Dateien sind nicht unbedingt Aktuelles beibehalten. Ihre Anwendung sollte Dateien aus diesem Verzeichnis entfernen, wenn es gilt, diese Dateien werden entfernt, da das OS nicht wann (oder auch wenn) garantiert.
+
+* * *| The OS kann den Inhalt dieses Verzeichnisses löschen, wenn es sich anfühlt, ist es erforderlich, aber verlassen Sie sich nicht dazu. Sie sollten dieses Verzeichnis entsprechend Ihrer Anwendung deaktivieren.
+
+### Android File System-Layout
+
+| Gerätepfad | `Cordova.file.*` | `AndroidExtraFileSystems` | R/w? | persistent? | OS löscht | Private |
+|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:-----------:|:---------:|:-------:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Ja |
+| `/ Data/Data/< app-Id > /` | applicationStorageDirectory | - | R/w | N/A | N/A | Ja |
+| `cache` | cacheDirectory | Cache | R/w | Ja | Ja * | Ja |
+| `files` | dataDirectory | Dateien | R/w | Ja | Nein | Ja |
+| `Documents` | | Dokumente | R/w | Ja | Nein | Ja |
+| `< Sdcard > /` | externalRootDirectory | sdcard | R/w | Ja | Nein | Nein |
+| `Android/data//` | externalApplicationStorageDirectory | - | R/w | Ja | Nein | Nein |
+| `cache` | externalCacheDirectry | Cache-extern | R/w | Ja | Nicht * * | Nein |
+| `files` | externalDataDirectory | Dateien-extern | R/w | Ja | Nein | Nein |
+
+* Das Betriebssystem kann regelmäßig dieses Verzeichnis zu löschen, aber verlasse dich nicht auf dieses Verhalten. Deaktivieren Sie den Inhalt dieses Verzeichnisses für Ihre Anwendung geeigneten. Ein Benutzer den Cache manuell löschen sollte, werden die Inhalte dieses Verzeichnisses entfernt.
+
+* * The OS nicht klar dieses Verzeichnis automatisch; Sie sind verantwortlich für die Inhalte selbst verwalten. Der Benutzer den Cache manuell löschen sollte, werden der Inhalt des Verzeichnisses entfernt.
+
+**Hinweis**: Wenn externe Speichergeräte nicht bereitgestellt werden kann, sind die `cordova.file.external*` Eigenschaften `null`.
+
+### BlackBerry 10-File-System-Layout
+
+| Gerätepfad | `Cordova.file.*` | R/w? | persistent? | OS löscht | Private |
+|:--------------------------------------------------- |:--------------------------- |:----:|:-----------:|:---------:|:-------:|
+| `file:///Accounts/1000/APPDATA/ < app Id > /` | applicationStorageDirectory | r | N/A | N/A | Ja |
+| `app/native` | applicationDirectory | r | N/A | N/A | Ja |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | R/w | Nein | Ja | Ja |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | R/w | Ja | Nein | Ja |
+| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | R/w | Ja | Nein | Nein |
+| `file:///Accounts/1000/Shared` | sharedDirectory | R/w | Ja | Nein | Nein |
+
+*Hinweis*: Wenn die Anwendung bereitgestellt wird, um Perimeter zu arbeiten, alle Pfade sind relativ /accounts/1000-enterprise.
+
+## Android Eigenarten
+
+### Android permanenten Speicherort
+
+Es gibt mehrere gültige Speicherorte, persistente Dateien auf einem Android-Gerät zu speichern. Finden Sie auf [dieser Seite][3] eine ausführliche Diskussion über die verschiedenen Möglichkeiten.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+Frühere Versionen des Plugins wählen würde, den Speicherort der temporären und permanenten Dateien beim Start, basierend auf, ob das Gerät behauptete, dass die SD-Karte (oder gleichwertige Speicherpartition) bereitgestellt wurde. Wenn die SD-Karte eingelegt wurde, oder wenn eine große interne Speicherpartition verfügbar war (wie auf Nexus-Geräten) und dann in die Wurzel dieses Raumes, die persistenten Dateien gespeichert werden. Dies bedeutete, dass alle Cordova apps aller verfügbaren Dateien auf der Karte sehen konnte.
+
+Wenn die SD-Karte nicht verfügbar war, dann Vorgängerversionen Daten unter speichern würde `/data/data/`, die isoliert Anwendungen voneinander, aber möglicherweise noch Ursache Daten zwischen Benutzern freigegeben werden.
+
+Es ist jetzt möglich, ob Sie Dateien der internen Datei-Speicherort oder unter Verwendung der bisherigen Logik, mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
+
+
+
+
+
+
+Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
+
+Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Wechseln die Location auf "Internal" würde bedeuten, dass Benutzer, die aktualisieren Sie ihre Anwendung, möglicherweise nicht auf ihre zuvor gespeicherte Dateien, abhängig von ihrem Gerät zugreifen.
+
+Wenn Ihre Anwendung neu ist, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die `Internal` Einstellung in der Regel empfohlen.
+
+## iOS Macken
+
+* `cordova.file.applicationStorageDirectory`ist schreibgeschützt; zum Speichern von Dateien im Stammverzeichnis der Versuch schlägt fehl. Verwenden Sie eine der anderen `cordova.file.*` für iOS definierten Eigenschaften (nur `applicationDirectory` und `applicationStorageDirectory` sind schreibgeschützt).
+* `FileReader.readAsText(blob, encoding)`
+ * Die `encoding` Parameter wird nicht unterstützt und UTF-8-Kodierung ist immer wirksam.
+
+### iOS permanenten Speicherort
+
+Es gibt zwei gültige Speicherorte persistente Dateien auf ein iOS-Gerät speichern: das Dokumenten-Verzeichnis und das Verzeichnis Library. Frühere Versionen des Plugins gespeichert immer nur persistente Dateien im Verzeichnis Dokumente. Dies hatte den Nebeneffekt einer Anwendung Dateien in iTunes, die oft unbeabsichtigte, speziell für Anwendungen, die viele kleine Dateien behandeln war, sichtbar zu machen, anstatt komplette Dokumente für den Export, die den beabsichtigten Zweck des Verzeichnisses ist zu produzieren.
+
+Es ist jetzt möglich, ob Sie Dateien in Dokumente oder Verzeichnis Library mit einer Präferenz in der Anwendung-`config.xml`-Datei speichern möchten. Hierzu fügen Sie eine dieser zwei Zeilen zu `"config.xml"`:
+
+
+
+
+
+
+Ohne diese Zeile wird das Datei Plugin `Compatibility` als Standard verwenden. Wenn ein Präferenz-Tag vorhanden ist, und nicht einen der folgenden Werte, wird die Anwendung nicht gestartet.
+
+Wenn Ihre Anwendung für Benutzer zuvor versandt wird, mithilfe eines älteren (Pre-1.0) Version dieses Plugins und gespeicherte Dateien im permanenten Dateisystem hat, dann sollten Sie die Einstellung zur `Compatibility` einstellen. Standort zur `Library` wechseln würde bedeuten, dass Benutzer, die ihre Anwendung aktualisieren nicht in der Lage wäre, ihre zuvor gespeicherte Dateien zugreifen.
+
+Wenn die Anwendung neu, oder nie zuvor Dateien im Dateisystem persistent gespeichert hat, wird die Einstellung der `Library` allgemein empfohlen.
+
+## Firefox OS Macken
+
+Der Datei-System-API wird von Firefox-OS nicht nativ unterstützt und wird als ein Shim auf IndexedDB implementiert.
+
+* Schlägt nicht fehl, wenn Sie nicht leere Verzeichnisse entfernen
+* Metadaten wird für Verzeichnisse nicht unterstützt.
+* Methoden `copyTo` und `moveTo` unterstützen keine Verzeichnisse
+
+Die folgenden Datenpfade werden unterstützt: * `applicationDirectory` - `xhr` verwendet, um lokale Dateien erhalten, die mit der app verpackt sind. *`dataDirectory` - für persistente app-spezifische Daten-Dateien. *`cacheDirectory` - Cache-Dateien, die app startet überleben sollte (Apps sollten nicht vom Betriebssystem zum Löschen von Dateien hier verlassen).
+
+## Browser-Eigenheiten
+
+### Gemeinsamen Macken und Bemerkungen
+
+* Jeder Browser verwendet ein eigene Sandbox Dateisystem. IE und Firefox verwenden IndexedDB als Basis. Alle Browser verwenden Schrägstrich als Verzeichnistrennzeichen in einem Pfad.
+* Directory-Einträge müssen nacheinander erstellt werden. Z. B. der Aufruf `fs.root.getDirectory ("dir1/Ordner2 ', {create:true}, SuccessCallback, ErrorCallback)` schlägt fehl, wenn dir1 nicht existierte.
+* Das Plugin fordert Benutzer die Berechtigung zum permanenten Speicher beim ersten Start Anwendung verwenden.
+* Plugin unterstützt `Cdvfile://localhost` (lokale Ressourcen) nur. D.h. externe Ressourcen nicht über `Cdvfile` unterstützt.
+* Das Plugin folgt nicht ["File System API 8.3 Naming Einschränkungen"][4].
+* BLOB und Datei "`close`-Funktion wird nicht unterstützt.
+* `FileSaver` und `BlobBuilder` werden von diesem Plugin nicht unterstützt und müssen nicht geboren.
+* Das Plugin unterstützt keine `RequestAllFileSystems`. Diese Funktion fehlt auch in den Spezifikationen.
+* Einträge im Verzeichnis werden nicht entfernt werden, wenn Sie verwenden `create: true` Flag für vorhandenes Verzeichnis.
+* Über Konstruktor erstellte Dateien werden nicht unterstützt. Sie sollten stattdessen die entry.file-Methode verwenden.
+* Jeder Browser verwendet eine eigene Form für Blob-URL-Verweise.
+* `readAsDataURL`-Funktion wird unterstützt, aber die Mediatype in Chrom hängt von der Eintrag Namenerweiterung, Mediatype im IE immer leer ist (das ist dasselbe wie `Text-Plain` gemäß der Spezifikation), Mediatype in Firefox ist immer `Application/Octet-Stream`. Beispielsweise, wenn der Inhalt `Abcdefg` gibt dann Firefox `Daten: Anwendung / Octet-Stream; base64, YWJjZGVmZw ==`, IE gibt `Daten:; base64, YWJjZGVmZw ==`, Chrom gibt `Daten: < Mediatype je nach Erweiterung des Eintragsnamens >; base64, YWJjZGVmZw ==`.
+* `ToInternalURL` gibt den Pfad zurück, in der Form `file:///persistent/path/to/entry` (Firefox, IE). Chrom gibt den Pfad zurück, in der Form `cdvfile://localhost/persistent/file`.
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### Chrom-Macken
+
+* Chrom-Dateisystem ist nicht sofort nach Gerät bereit. Als Workaround können Sie `FilePluginIsReady`-Ereignis abonnieren. Beispiel:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+`Window.isFilePluginReadyRaised`-Funktion können Sie überprüfen, ob Ereignis bereits ausgelöst wurde. -window.requestFileSystem temporär und PERSISTENTE Dateisystem-Quoten sind nicht begrenzt, in Chrom. -Um die dauerhafte Speicherung in Chrom zu erhöhen benötigen Sie `window.initPersistentFileSystem`-Methode aufrufen. Permanenter Speicherkontingent beträgt 5 MB standardmäßig. -Chrome erforderlich `--erlauben-Datei-Zugriff-aus-Files` Argument an den Support API via `file:///` Protokoll führen. -`Datei`-Objekt wird nicht geändert werden, wenn Sie Flag verwenden `{create:true}` als einen vorhandenen `Eintrag` zu erhalten. -Veranstaltungen `cancelable`-Eigenschaft festgelegt ist in Chrom wahr. Dies widerspricht der [Spezifikation][5]. -`toURL`-Funktion in Chrome zurück `Dateisystem:`-Pfad je nach Anwendungshost vorangestellt. Z. B. `filesystem:file:///persistent/somefile.txt`, `Filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` Funktionsergebnis enthält keine nachgestellten Schrägstrich bei Verzeichniseintrag. Chrom löst Verzeichnisse mit Schrägstrich-gezogene Urls aber korrekt. -`ResolveLocalFileSystemURL`-Methode erfordert die eingehenden `Url` `Dateisystem` Präfix haben. Beispielsweise sollte die `Url`-Parameter für `ResolveLocalFileSystemURL` in der Form `filesystem:file:///persistent/somefile.txt` im Gegensatz zu der Form `file:///persistent/somefile.txt` in Android. -Veraltete `ToNativeURL`-Funktion wird nicht unterstützt und muss keinen Stub. -`SetMetadata`-Funktion ist nicht in den Spezifikationen angegeben und nicht unterstützt. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, statt SYNTAX_ERR(code: 8) auf anfordern des Dateisystems nicht existent. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt PATH_EXISTS_ERR(code: 12) zu versuchen, die ausschließlich eine Datei oder ein Verzeichnis zu erstellen, die bereits vorhanden ist. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NO_MODIFICATION_ALLOWED_ERR(code: 6) zu versuchen, rufen Sie RemoveRecursively auf das Root-Dateisystem. -INVALID_MODIFICATION_ERR (Code: 9) wird ausgelöst, anstatt NOT_FOUND_ERR(code: 1) zu versuchen, MoveTo-Verzeichnis, das nicht vorhanden ist.
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### Auf der Grundlage von IndexedDB Impl Macken (Firefox und IE)
+
+* `.` und `.` werden nicht unterstützt.
+* IE unterstützt keine `file:///`-Modus; nur der Modus für gehostete ist unterstützten (Http://localhost:xxxx).
+* Firefox Dateisystem Größe ist nicht begrenzt, aber jede 50MB-Erweiterung wird eine Benutzer die Berechtigung anzufordern. IE10 können bis zu 10mb kombinierte AppCache und IndexedDB in Implementierung des Dateisystems verwendet, ohne Aufforderung, sobald Sie dieses Niveau, werden, das Sie aufgefordert werden schlagen, wenn Sie es bis Max 250 mb pro Standort erhöht werden sollen. `Size`-Parameter für `RequestFileSystem` Funktion wirkt also nicht Dateisystem in Firefox und IE.
+* `ReadAsBinaryString` Funktion heißt es nicht in die Angaben und in IE nicht unterstützt und muss keinen Stub.
+* `file.Type` ist immer null.
+* Sie sollten nicht erstellen Eintrag mit DirectoryEntry Instanz Rückrufergebnis, die gelöscht wurde. Andernfalls erhalten Sie einen "hängende Eintrag".
+* Bevor Sie eine Datei lesen können, die gerade geschrieben wurde, müssen Sie eine neue Instanz dieser Datei erhalten.
+* `SetMetadata`-Funktion, die nicht in den Specs genannt unterstützt Feldänderung nur `ModificationTime`.
+* `CopyTo` und `MoveTo`-Funktionen unterstützen keine Verzeichnisse.
+* Verzeichnisse-Metadaten werden nicht unterstützt.
+* Beide Entry.remove und directoryEntry.removeRecursively nicht scheitern, wenn nicht leere Verzeichnisse entfernen - Verzeichnisse entfernt werden stattdessen zusammen mit Inhalt gereinigt.
+* `abort` und `truncate`-Funktionen werden nicht unterstützt.
+* Progress-Ereignisse werden nicht ausgelöst. Beispielsweise wird dieser Handler nicht ausgeführt werden:
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## Upgrade Notes
+
+In v1.0.0 dieses Plugins haben die `FileEntry` und `DirectoryEntry` Strukturen geändert, um mehr im Einklang mit der veröffentlichten Spezifikation sein.
+
+Vorgängerversionen (Pre-1.0.0) des Plugins den Gerät-Absolute-Dateispeicherort in der Eigenschaft `fullPath` `Entry` Objekte gespeichert. Diese Pfade würde in der Regel aussehen
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Diese Pfade wurden auch von der `toURL()`-Methode der `Entry` Objekte zurückgegeben.
+
+Mit v1.0.0 ist das `fullPath`-Attribut den Pfad zu der Datei, *relativ zum Stammverzeichnis des Dateisystems HTML*. Also, würde die oben genannten Wege jetzt beide durch ein `FileEntry`-Objekt mit einem `fullPath` von dargestellt werden
+
+ /path/to/file
+
+
+Wenn Ihre Anwendung mit absoluter Gerätepfade arbeitet und Sie zuvor diese Pfade durch die Eigenschaft `fullPath` `Entry` Objekte abgerufen, sollten dann Sie den Code, um stattdessen `entry.toURL()` verwenden aktualisieren.
+
+Für rückwärts Kompatibilität, die `resolveLocalFileSystemURL()`-Methode wird einen Absolute-Gerätepfad zu akzeptieren und kehrt ein `Entry`-Objekt entspricht, solange diese Datei in den `TEMPORARY` oder `PERSISTENT` Dateisysteme existiert.
+
+Dies wurde vor allem ein Problem mit dem File-Transfer-Plugin, die zuvor-Absolute-Gerätepfade verwendet (und kann damit noch einverstanden). Es wurde überarbeitet, um mit Dateisystem-URLs korrekt zu arbeiten, damit ersetzen `entry.fullPath` mit `entry.toURL()` immer das Plugin zum Arbeiten mit Dateien auf dem Gerät Probleme lösen sollte.
+
+In v1.1.0 wurde der Rückgabewert von `toURL()` (siehe \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) geändert, um eine absolute "file://" URL zurückgeben. wo immer möglich. Sicherstellung einer ' Cdvfile:'-URL können Sie an `toInternalURL()`. Diese Methode gibt jetzt Dateisystem URLs der Form zurück.
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+die benutzt werden können, um die Datei eindeutig zu identifizieren.
+
+## Liste der Fehlercodes und Bedeutungen
+
+Wenn ein Fehler ausgelöst wird, wird eines der folgenden Codes verwendet werden.
+
+| Code | Konstante |
+| ----:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Konfigurieren das Plugin (Optional)
+
+Die Menge der verfügbaren Dateisysteme kann pro Plattform konfiguriert sein. Erkennen von iOS und Android ein Tag in `"config.xml"` die Namen der Dateisysteme installiert werden. Standardmäßig sind alle Datei-System-Roots aktiviert.
+
+
+
+
+
+### Android
+
+* `files`: interne Datei-Speicher-Verzeichnis der Anwendung
+* `files-external`: Verzeichnis der Anwendung externe Datei Speicher
+* `sdcard`: das externe Globaldatei-Speicherverzeichnis (Dies ist die Wurzel der SD-Karte, sofern installiert). Sie benötigen die Berechtigung zur Verwendung dieses `android.permission.WRITE_EXTERNAL_STORAGE`.
+* `cache`: internen Cache-Verzeichnis der Anwendung
+* `cache-external`: externer Cache-Verzeichnis der Anwendung
+* `root`: das gesamte Gerät-Dateisystem
+
+Android unterstützt auch eine spezielle Dateisystem mit dem Namen "documents", die ein Unterverzeichnis "/Documents/" die "files" Dateisystem darstellt.
+
+### iOS
+
+* `library`: Bibliothek-Verzeichnis der Anwendung
+* `documents`: Dokumente-Verzeichnis der Anwendung
+* `cache`: Cache-Verzeichnis der Anwendung
+* `bundle`: die Anwendung Bündel; den Speicherort der die app selbst auf dem Datenträger (schreibgeschützt)
+* `root`: das gesamte Gerät-Dateisystem
+
+Standardmäßig können die Bibliothek und Dokumenten-Verzeichnisse mit iCloud synchronisiert werden. Sie können auch verlangen, zwei zusätzliche Dateisysteme, `library-nosync` und `documents-nosync`, die einem speziellen nicht synchronisierten Verzeichnis innerhalb darstellen der `/Library` oder `/Documents`-Dateisystem.
diff --git a/plugins/cordova-plugin-file/doc/de/plugins.md b/plugins/cordova-plugin-file/doc/de/plugins.md
new file mode 100644
index 0000000..8887d7a
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/de/plugins.md
@@ -0,0 +1,101 @@
+
+
+# Hinweise für Plugin-Entwickler
+
+Diese Notizen sind hauptsächlich für Android und iOS-Entwickler, die Plugins welche Schnittstelle mit dem Dateisystem, mit dem Plugin Datei schreiben möchten.
+
+## Arbeiten mit Cordova-Datei-System-URLs
+
+Seit der Version 1.0.0, wurde dieses Plugin verwendet URLs mit einer `cdvfile` Regelung für die gesamte Kommunikation über die Brücke, sondern als raw-Device Dateisystempfade zu JavaScript auszusetzen.
+
+Auf der Seite JavaScript bedeutet dies, dass FileEntries und DirectoryEntry-Objekt ein FullPath-Attribut haben, die relativ zum Stammverzeichnis des Dateisystems HTML ist. Wenn Ihr Plugins-JavaScript-API ein FileEntries oder DirectoryEntry-Objekt akzeptiert, rufen Sie `.toURL()` auf das Objekt vor der Übergabe an systemeigenen Code über die Brücke.
+
+### Konvertieren von Cdvfile: / / URLs auf Fileystem Pfade
+
+Plugins, die auf das Dateisystem schreiben müssen, sollten eine empfangene Datei-System-URL auf eine tatsächliche Stelle des Dateisystems zu konvertieren. Es gibt mehrere Wege, dies zu tun, je nach einheitlichen Plattform.
+
+Es ist wichtig, daran erinnern, dass nicht alle `cdvfile://` URLs sind zuweisbaren real Dateien auf das Gerät. Einige URLs verweisen auf Vermögenswerte auf Gerät nicht durch Dateien dargestellt werden, oder sogar auf Remoteressourcen verweisen können. Aufgrund dieser Möglichkeiten sollten Plugins immer testen, ob sie ein sinnvolles Ergebnis zu erhalten, wieder bei dem Versuch, die URLs in Pfade umwandeln.
+
+#### Android
+
+Auf Android, konvertiert die einfachste Methode eine `cdvfile://` URL zu einem Dateisystempfad zu verwenden ist `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`verfügt über mehrere Methoden der verarbeiten kann `cdvfile://` URLs:
+
+ WebView ist Mitglied der Plugin-Klasse CordovaResourceApi ResourceApi = webView.getResourceApi();
+
+ Erhalten eine file:/// URL, diese Datei auf dem Gerät / / oder die gleiche URL unverändert, wenn es eine Datei-Uri FileURL zugeordnet werden kann nicht = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+Es ist auch möglich, das Plugin Datei direkt zu verwenden:
+
+ Import org.apache.cordova.file.FileUtils;
+ Import org.apache.cordova.file.FileSystem;
+ Import Java.net.MalformedURLException:;
+
+ Erhalten Sie das Datei-Plugin aus dem Plugin-Manager FileUtils FilePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ Angesichts eine URL, einen Pfad zu erhalten, denn es versuchen {String Pfad = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / die Dateisystem-Url war nicht erkannt}
+
+
+Aus einem Pfad zu konvertieren eine `cdvfile://` URL:
+
+ Import org.apache.cordova.file.LocalFilesystemURL;
+
+ Rufen Sie ein LocalFilesystemURL-Objekt für einen Gerätepfad / / oder null, wenn sie nicht als URL Cdvfile dargestellt wird.
+ LocalFilesystemURL Url = filePlugin.filesystemURLforLocalPath(path);
+ Erhalten Sie die Zeichenfolgendarstellung der URL Objekt String CdvfileURL = url.toString();
+
+
+Wenn Ihr Plugin eine Datei erstellt, und Sie dafür ein FileEntries-Objekt zurückgeben möchten, verwenden Sie das Datei-Plugin:
+
+ Zurückgeben eine JSON-Struktur geeignet für die Rückgabe an JavaScript, / / oder null, wenn diese Datei nicht als URL Cdvfile darstellbar ist.
+ JSONObject Eintrag = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+Cordova auf iOS verwendet nicht das gleiche `CordovaResourceApi` Konzept als Android. Auf iOS sollten Sie das Datei-Plugin verwenden, zum Konvertieren von URLs und Dateisystem-Pfaden.
+
+ Rufen Sie ein CDVFilesystem URL-Objekt von einer URL-Zeichenfolge CDVFilesystemURL * Url = [CDVFilesystemURL FileSystemURLWithString:cdvfileURL];
+ Erhalten Sie einen Pfad für die URL-Objekt oder NULL, wenn es einen Dateipfad NSString * zugeordnet werden kann nicht = [FilePlugin FilesystemPathForURL:url];
+
+
+ Eine CDVFilesystem URL-Objekt für einen Gerätepfad abrufen oder / / gleich NULL, wenn sie nicht als URL Cdvfile dargestellt wird.
+ CDVFilesystemURL-Url = [FilePlugin FileSystemURLforLocalPath:path];
+ Erhalten Sie die Zeichenfolgendarstellung der URL Objekt NSString * CdvfileURL = [Url AbsoluteString];
+
+
+Wenn Ihr Plugin eine Datei erstellt, und Sie dafür ein FileEntries-Objekt zurückgeben möchten, verwenden Sie das Datei-Plugin:
+
+ Eine CDVFilesystem URL-Objekt für einen Gerätepfad abrufen oder / / gleich NULL, wenn sie nicht als URL Cdvfile dargestellt wird.
+ CDVFilesystemURL-Url = [FilePlugin FileSystemURLforLocalPath:path];
+ Erhalten eine Struktur zurück nach JavaScript NSDictionary * Eintrag = [FilePlugin MakeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+In JavaScript, bekommen eine `cdvfile://` URL aus einem FileEntries oder DirectoryEntry-Objekt, rufen Sie einfach `.toURL()` drauf:
+
+ Var CdvfileURL = entry.toURL();
+
+
+Im Plugin Antwort Handler zur Konvertierung von einer zurückgegebenen FileEntries-Struktur in einem tatsächlichen Eintrag-Objekt sollte Handlercode importieren die Datei-Erweiterung und ein neues Objekt zu erstellen:
+
+ Erstellen Sie entsprechenden Eintrag Objekt Var Eintrag;
+ Wenn (entryStruct.isDirectory) {Eintrag = neues DirectoryEntry (entryStruct.name, entryStruct.fullPath, neue FileSystem(entryStruct.filesystemName));} sonst {Eintrag = neue FileEntries (entryStruct.name, entryStruct.fullPath, neue FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/es/README.md b/plugins/cordova-plugin-file/doc/es/README.md
new file mode 100644
index 0000000..2a653bf
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/es/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+Este plugin implementa una API de archivo que permite acceso de lectura/escritura a los archivos que residen en el dispositivo.
+
+Este plugin se basa en varias especificaciones, incluyendo: el HTML5 archivo API
+
+Los directorios (ahora extinto) y sistema de extensiones más recientes: aunque la mayor parte del código del plugin fue escrito cuando una especificación anterior era actual:
+
+También implementa la especificación de FileWriter:
+
+Para el uso, por favor, consulte 'HTML5 Rocks excelente [FileSystem artículo.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+Para tener una visión general de otras opciones de almacenamiento, consulte [Guía de almacenamiento Cordova](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+Este plugin define global `cordova.file` objeto.
+
+Aunque en el ámbito global, no estará disponible hasta después de la `deviceready` evento.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Instalación
+
+ cordova plugin add cordova-plugin-file
+
+
+## Plataformas soportadas
+
+ * Amazon fire OS
+ * Android
+ * BlackBerry 10
+ * Firefox OS
+ * iOS
+ * Windows Phone 7 y 8 *
+ * Windows 8 *
+ * Windows*
+ * Explorador
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## Donde almacenar los archivos
+
+A partir de v1.2.0, URLs a directorios de sistema de archivos importantes son proporcionadas. Cada dirección URL está en la forma *file:///path/to/spot/*y se puede convertir en un `DirectoryEntry` usando`window.resolveLocalFileSystemURL()`.
+
+ * `cordova.file.applicationDirectory`-Directorio Read-only donde está instalada la aplicación. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.applicationStorageDirectory`-Directorio del entorno limitado de la aplicación; en iOS esta ubicación es de sólo lectura (pero subdirectorios específicos [como `/Documents` ] son de lectura y escritura). Todos los datos contenidos dentro es privado para la aplicación. ( *iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.dataDirectory`-Almacenamiento de datos persistente y privadas dentro de entorno limitado de la aplicación utilizando la memoria interna (en Android, si necesitas usar memoria externa, use `.externalDataDirectory` ). En iOS, este directorio no está sincronizado con iCloud (utilice `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.cacheDirectory`-Directorio para los archivos de datos almacenados en caché o los archivos que su aplicación puede volver a crear fácilmente. El sistema operativo puede borrar estos archivos cuando el dispositivo se agota en almacenamiento de información, sin embargo, aplicaciones no deben confiar en el sistema operativo para eliminar los archivos de aquí. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-Espacio aplicación de almacenamiento externo. (*Android*)
+
+ * `cordova.file.externalDataDirectory`¿Dónde poner los archivos de datos específicos de la aplicación de almacenamiento externo. (*Android*)
+
+ * `cordova.file.externalCacheDirectory`-Caché aplicación de almacenamiento externo. (*Android*)
+
+ * `cordova.file.externalRootDirectory`-Raíz de almacenamiento externo (tarjeta SD). (*Android*, *BlackBerry 10*)
+
+ * `cordova.file.tempDirectory`-Directorio temporal que puede borrar el sistema operativo en sí. No confíe en el sistema operativo para borrar este directorio; su aplicación siempre debe eliminar archivos según corresponda. (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-Contiene los archivos de la aplicación específica que deben ser sincronizados (e.g. a iCloud). (*iOS*)
+
+ * `cordova.file.documentsDirectory`-Archivos privados a la aplicación, pero que son significativos para otra aplicación (por ejemplo archivos de Office). (*iOS*)
+
+ * `cordova.file.sharedDirectory`-Archivos disponibles globalmente para todas las aplicaciones (*BlackBerry 10*)
+
+## Diseños de sistema de archivo
+
+Aunque técnicamente un detalle de la implementación, puede ser muy útil saber cómo la `cordova.file.*` mapa de propiedades en trazados físicos en un dispositivo real.
+
+### iOS diseño de sistema de archivo
+
+| Ruta de dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | sincronización | privado |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:-------------:|:--------------:|:-------:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N / A | N / A | N / A | Sí |
+| `appname.app/` | applicationDirectory | Bundle | r | N / A | N / A | N / A | Sí |
+| `www/` | - | - | r | N / A | N / A | N / A | Sí |
+| `Documents/` | documentsDirectory | documentos | r/w | Sí | No | Sí | Sí |
+| `NoCloud/` | - | documentos-nosync | r/w | Sí | No | No | Sí |
+| `Library` | - | Biblioteca | r/w | Sí | No | ¿Sí? | Sí |
+| `NoCloud/` | dataDirectory | Biblioteca-nosync | r/w | Sí | No | No | Sí |
+| `Cloud/` | syncedDataDirectory | - | r/w | Sí | No | Sí | Sí |
+| `Caches/` | cacheDirectory | caché | r/w | Sí * | Yes**\* | No | Sí |
+| `tmp/` | tempDirectory | - | r/w | No** | Yes**\* | No | Sí |
+
+\ * Archivos persisten a través de reinicios de aplicación y actualizaciones, pero este directorio puede ser despejó cuando el OS deseos. Su aplicación debe ser capaz de recrear cualquier contenido que puede ser eliminado.
+
+** Archivos puede persistir a través de la aplicación se reinicia, pero no confiar en este comportamiento. Los archivos no se garantizan que persisten a través de actualizaciones. Su aplicación debe eliminar los archivos de este directorio cuando es aplicable, como el sistema operativo no garantiza cuando (o incluso si) estos archivos se quitan.
+
+**\ * OS la puede borrar el contenido de este directorio siempre que se siente es necesario, pero no dependen de esto. Debe borrar este directorio según sea apropiado para su aplicación.
+
+### Disposición del sistema Android File
+
+| Ruta de dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | privado |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:-----:|:-------------:|:----------:|:-------:|
+| `File:///android_asset/` | applicationDirectory | | r | N / A | N / A | Sí |
+| `/Data/data/< id de aplicación > /` | applicationStorageDirectory | - | r/w | N / A | N / A | Sí |
+| `cache` | cacheDirectory | caché | r/w | Sí | Sí \ * | Sí |
+| `files` | dataDirectory | archivos | r/w | Sí | No | Sí |
+| `Documents` | | documentos | r/w | Sí | No | Sí |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sí | No | No |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sí | No | No |
+| `cache` | externalCacheDirectry | caché-externo | r/w | Sí | No** | No |
+| `files` | externalDataDirectory | archivos externos | r/w | Sí | No | No |
+
+\ * El sistema operativo periódicamente puede borrar este directorio, pero no confiar en este comportamiento. Borrar el contenido de este directorio según sea apropiado para su aplicación. El contenido de este directorio debe un usuario purga la caché manualmente, se eliminan.
+
+** El sistema operativo no borrar este directorio automáticamente; usted es responsable de administrar el contenido usted mismo. Deberá el usuario purga la caché manualmente, se extraen los contenidos del directorio.
+
+**Nota**: Si no se puede montar de almacenamiento externo, el `cordova.file.external*` Propiedades`null`.
+
+### Disposición del sistema blackBerry 10 archivo
+
+| Ruta de dispositivo | `Cordova.file.*` | ¿r/w? | ¿persistente? | OS despeja | privado |
+|:------------------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:----------:|:-------:|
+| `File:///accounts/1000/AppData/ < id de aplicación > /` | applicationStorageDirectory | r | N / A | N / A | Sí |
+| `app/native` | applicationDirectory | r | N / A | N / A | Sí |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sí | Sí |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sí | No | Sí |
+| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sí | No | No |
+| `File:///accounts/1000/shared` | sharedDirectory | r/w | Sí | No | No |
+
+*Nota*: cuando se implementa la aplicación al trabajo de perímetro, todos los caminos son relativos a /accounts/1000-enterprise.
+
+## Rarezas Android
+
+### Ubicación de almacenamiento persistente Android
+
+Hay múltiples ubicaciones válidas para almacenar archivos persistentes en un dispositivo Android. Vea [esta página](http://developer.android.com/guide/topics/data/data-storage.html) para una extensa discusión de las distintas posibilidades.
+
+Las versiones anteriores del plugin elegiría la ubicación de los archivos temporales y persistentes en el arranque, basado en si el dispositivo afirmó que fue montado en la tarjeta SD (o partición de almacenamiento equivalente). Si fue montada en la tarjeta SD, o una partición de gran almacenamiento interno estaba disponible (como en dispositivos de Nexus,) y luego los archivos persistentes se almacenaría en la raíz de ese espacio. Esto significaba que todas las apps Cordova podían ver todos los archivos disponibles en la tarjeta.
+
+Si la tarjeta SD no estaba disponible, entonces versiones anteriores podría almacenar datos debajo de `/data/data/` , que aísla las apps del otro, pero puede todavía causa datos para ser compartido entre los usuarios.
+
+Ahora es posible elegir si desea almacenar archivos en la ubicación de almacenamiento del archivo interno, o usando la lógica anterior, con una preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` :
+
+
+
+
+
+
+Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación.
+
+Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación para "Internal" significa que los usuarios existentes que actualización su aplicación pueden ser incapaces de acceder a sus archivos previamente almacenadas, dependiendo de su dispositivo.
+
+Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Internal` generalmente se recomienda el ajuste.
+
+### Operaciones recursivas lento para /android_asset
+
+Listado de directorios activos es realmente lento en Android. Usted puede acelerar hacia arriba, agregando `src/android/build-extras.gradle` a la raíz de tu proyecto android (también requiere de cordova-android@4.0.0 o mayor).
+
+## iOS rarezas
+
+ * `cordova.file.applicationStorageDirectory`es de sólo lectura; intentar almacenar archivos en el directorio raíz fallará. Utilice uno de los `cordova.file.*` las propiedades definidas para iOS (sólo `applicationDirectory` y `applicationStorageDirectory` son de sólo lectura).
+ * `FileReader.readAsText(blob, encoding)`
+ * El `encoding` no se admite el parámetro, y codificación UTF-8 es siempre en efecto.
+
+### iOS ubicación de almacenamiento persistente
+
+Hay dos ubicaciones válidas para almacenar archivos persistentes en un dispositivo iOS: el directorio de documentos y el directorio de biblioteca. Las versiones anteriores del plugin sólo almacenan archivos persistentes en el directorio de documentos. Esto tenía el efecto secundario de todos los archivos de la aplicación haciendo visible en iTunes, que era a menudo involuntarios, especialmente para aplicaciones que manejan gran cantidad de archivos pequeños, en lugar de producir documentos completos para la exportación, que es la finalidad del directorio.
+
+Ahora es posible elegir si desea almacenar archivos en los documentos o directorio de bibliotecas, con preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` :
+
+
+
+
+
+
+Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación.
+
+Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación de `Library` significa que los usuarios existentes que actualización su aplicación sería incapaces de acceder a sus archivos previamente almacenadas.
+
+Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Library` generalmente se recomienda el ajuste.
+
+## Firefox OS rarezas
+
+La API de sistema de archivo de forma nativa no es compatible con Firefox OS y se implementa como una cuña en la parte superior indexedDB.
+
+ * No falla cuando eliminar directorios no vacía
+ * No admite metadatos para directorios
+ * Los métodos `copyTo` y `moveTo` no son compatibles con directorios
+
+Se admiten las siguientes rutas de datos: * `applicationDirectory` -usa `xhr` para obtener los archivos locales que están envasados con la aplicación. * `dataDirectory` - Para archivos de datos específicos de aplicación persistente. * `cacheDirectory` -En caché archivos que deben sobrevivir se reinicia la aplicación (aplicaciones no deben confiar en el sistema operativo para eliminar archivos aquí).
+
+## Navegador rarezas
+
+### Rarezas y observaciones comunes
+
+ * Cada navegador utiliza su propio sistema de ficheros un espacio aislado. IE y Firefox utilizan IndexedDB como base. Todos los navegadores utilizan diagonal como separador de directorio en un camino.
+ * Las entradas de directorio deben crearse sucesivamente. Por ejemplo, la llamada `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` se producirá un error si no existiera dir1.
+ * El plugin solicita permiso de usuario para usar almacenamiento persistente en el primer comienzo de la aplicación.
+ * Plugin soporta `cdvfile://localhost` (recursos locales) solamente. Es decir, no se admiten los recursos externos vía `cdvfile`.
+ * El plugin no sigue ["Archivo sistema API 8.3 nombrando restricciones"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
+ * BLOB y archivo ' `close` la función no es compatible.
+ * `FileSaver` y `BlobBuilder` no son compatibles con este plugin y no tengo recibos.
+ * El plugin no es compatible con `requestAllFileSystems`. Esta función también está desaparecida en las especificaciones.
+ * No se quitarán las entradas de directorio Si utilizas `create: true` bandera de directorio existente.
+ * No se admiten archivos creados mediante el constructor. Debe utilizar método entry.file en su lugar.
+ * Cada navegador utiliza su propia forma de blob URL referencias.
+ * se admite la función `readAsDataURL`, pero el mediatype en cromo depende de la extensión de nombre de entrada, mediatype en IE siempre está vacío (que es lo mismo como `plain-text` según la especificación), el mediatype en Firefox siempre es `application/octet-stream`. Por ejemplo, si el contenido es `abcdefg` entonces Firefox devuelve `datos: aplicación / octet-stream; base64, YWJjZGVmZw ==`, es decir devuelve `datos:; base64, YWJjZGVmZw ==`, cromo devuelve `datos: < mediatype dependiendo de la extensión de nombre de la entrada >; base64, YWJjZGVmZw ==`.
+ * `toInternalURL` devuelve la ruta de la forma `file:///persistent/path/to/entry` (Firefox, IE). Cromo devuelve la ruta de acceso en el formulario `cdvfile://localhost/persistent/file`.
+
+### Rarezas de Chrome
+
+ * Filesystem de Chrome no es inmediatamente después de evento ready dispositivo. Como solución temporal puede suscribirse al evento `filePluginIsReady`. Ejemplo:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+Puede utilizar la función `window.isFilePluginReadyRaised` para verificar si ya se provoca el evento. -window.requestFileSystem temporal y persistente filesystem cuotas no están limitadas en cromo. -Para aumentar el almacenamiento persistente en cromo necesitas llamar el método `window.initPersistentFileSystem`. Cuota de almacenamiento persistente es de 5 MB por defecto. -Chrome requiere `--permitir-archivo-acceso-de-archivos` ejecutar argumento al soporte API mediante protocolo `file:///`. -`Archivo` objeto no cambiará si utilizas bandera `{create:true}` cuando una `entrada` de existente. -eventos `cancelable` propiedad está establecida en true en cromo. Esto es contrario a la [Especificación](http://dev.w3.org/2009/dap/file-system/file-writer.html). -función de `toURL` en Chrome devuelve `filesystem:`-prefijo camino dependiendo de host de la aplicación. Por ejemplo, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -resultado de la función de `toURL` no contiene barra en caso de entrada en el directorio. Cromo resuelve directorios con urls slash-siguió correctamente sin embargo. -método `resolveLocalFileSystemURL` requiere la entrantes `url` que tienen prefijo `filesystem`. Por ejemplo, el parámetro de `url` para `resolveLocalFileSystemURL` debería estar en la forma `filesystem:file:///persistent/somefile.txt` en comparación con la forma `file:///persistent/somefile.txt` en Android. -Obsoleto `toNativeURL` función no es compatible y no tiene un trozo. -función de `setMetadata` no es indicada en las especificaciones y no admite. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de SYNTAX_ERR(code: 8) a petición de un sistema de ficheros inexistentes. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de PATH_EXISTS_ERR(code: 12) en intentar exclusivamente crear un archivo o directorio, que ya existe. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de NO_MODIFICATION_ALLOWED_ERR(code: 6) para tratar de llamar a removeRecursively en el sistema de archivos raíz. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de NOT_FOUND_ERR(code: 1) en tratar de moveTo directorio que no existe.
+
+### Impl base IndexedDB rarezas (IE y Firefox)
+
+ * `.` y `..` no son compatibles.
+ * IE no soporta `file:///`-modo; modo alojado sólo es compatible (http://localhost:xxxx).
+ * Tamaño del sistema de archivos de Firefox no es limitada pero cada extensión de 50 MB solicitará un permiso de usuario. IE10 permite hasta 10mb de combinados AppCache y IndexedDB utilizados en la implementación del sistema de ficheros sin preguntar, cuando llegas a ese nivel que se le preguntará si desea permitir que ser aumentada hasta un máximo de 250 mb por sitio. Para que `size` parámetro para la función `requestFileSystem` no afecta sistema de ficheros en Firefox y IE.
+ * la función `readAsBinaryString` no se indica en las especificaciones y no compatible con IE y no tiene un trozo.
+ * `file.type` siempre es null.
+ * No debe crear entrada utilizando DirectoryEntry resultado de devolución de llamada de instancia que fue borrado. De lo contrario, obtendrá una entrada' colgar'.
+ * Antes de que se puede leer un archivo, el cual fue escrito sólo que necesitas una nueva instancia de este archivo.
+ * la función `setMetadata`, que no es indicada en las especificaciones soporta sólo el cambio de campo `modificationTime`.
+ * `copyTo` y `moveTo` funciones no son compatibles con directorios.
+ * Metadatos de directorios no es compatible.
+ * Tanto Entry.remove y directoryEntry.removeRecursively no fallan al retirar no vacía directorios - directorios de ser eliminados se limpian junto con contenido en su lugar.
+ * `abort` y `truncate` las funciones no son compatibles.
+ * eventos de progreso no están despedidos. Por ejemplo, este controlador no ejecutará:
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## Actualización de notas
+
+En v1.0.0 de este plugin, han cambiado las estructuras `FileEntry` y `DirectoryEntry`, para estar más acorde con las especificaciones publicadas.
+
+Versiones anteriores (pre-1.0.0) del plugin almacenan el dispositivo-absoluto-archivo-ubicación en la propiedad `fullPath` de objetos de `entrada`. Estos caminos típicamente parecería
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Estas rutas también fueron devueltos por el método `toURL()` de los objetos de `entrada`.
+
+Con v1.0.0, el atributo `fullPath` es la ruta del archivo, *relativo a la raíz del sistema de archivos HTML*. Así, los caminos más arriba sería ahora ambos ser representado por un objeto `FileEntry` con un `fullPath` de
+
+ /path/to/file
+
+
+Si su aplicación funciona con dispositivo-absoluto-caminos, y previamente obtenido esos caminos a través de la propiedad `fullPath` de objetos de `Entry`, deberá actualizar el código para utilizar `entry.toURL()` en su lugar.
+
+Para atrás compatibilidad, el método `resolveLocalFileSystemURL()` a aceptar un dispositivo-absoluto-trayectoria y devolverá un objeto de `Entry` correspondiente que, mientras exista ese archivo dentro de los sistemas de ficheros `TEMPORARY` o la `PERSISTENT`.
+
+Esto ha sido particularmente un problema con el plugin de transferencia de archivos, que anteriormente utilizado dispositivo-absoluto-caminos (y todavía puede aceptarlas). Ha sido actualizado para funcionar correctamente con sistema de ficheros URLs, para reemplazar `entry.fullPath` con `entry.toURL()` debe resolver cualquier problema conseguir ese plugin para trabajar con archivos en el dispositivo.
+
+En v1.1.0 el valor devuelto por `toURL()` fue cambiado (consulte \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) para devolver una dirección URL absoluta 'file://'. siempre que sea posible. Para asegurar una ' cdvfile:'-URL ahora puede utilizar `toInternalURL()`. Este método devolverá ahora filesystem URLs de la forma
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+que puede utilizarse para identificar el archivo únicamente.
+
+## Lista de códigos de Error y significados
+
+Cuando se produce un error, uno de los siguientes códigos se utilizará.
+
+| Código | Constante |
+| ------:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configurando el Plugin (opcional)
+
+El conjunto de los sistemas de ficheros disponibles puede ser configurado por plataforma. Tanto iOS y Android reconocen un etiqueta en el `archivo config.xml` que nombra a los sistemas de archivos para ser instalado. De forma predeterminada, se activan todas las raíces del sistema de archivos.
+
+
+
+
+
+### Android
+
+ * `files`: directorio de almacenamiento de archivo interno de la aplicación
+ * `files-external`: directorio de almacenamiento de archivo externo de la aplicación
+ * `sdcard`: el directorio de almacenamiento de archivo externo global (esta es la raíz de la tarjeta SD, si uno está instalado). Debe tener el permiso de `android.permission.WRITE_EXTERNAL_STORAGE` a usar esto.
+ * `cache`: directorio de memoria caché interna de la aplicación
+ * `cache-external`: directorio de caché externo de la aplicación
+ * `root`: el sistema de archivos de todo el dispositivo
+
+Android también es compatible con un sistema de archivos especial llamado "documents", que representa un subdirectorio "/Documents/" dentro del sistema de archivos "archivos".
+
+### iOS
+
+ * `library`: directorio de bibliotecas de la aplicación
+ * `documents`: directorio de documentos de la aplicación
+ * `cache`: directorio de caché de la aplicación
+ * `bundle`: paquete de la aplicación; la ubicación de la aplicación en sí mismo en el disco (sólo lectura)
+ * `root`: el sistema de archivos de todo el dispositivo
+
+De forma predeterminada, los directorios de documentos y la biblioteca pueden ser sincronizados con iCloud. También puede solicitar dos sistemas adicionales, `library-nosync` y `documents-nosync`, que representan un directorio especial no sincronizados dentro de la `/Library` o sistema de ficheros `/Documents`.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/es/index.md b/plugins/cordova-plugin-file/doc/es/index.md
new file mode 100644
index 0000000..a9c0264
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/es/index.md
@@ -0,0 +1,336 @@
+
+
+# cordova-plugin-file
+
+Este plugin implementa una API de archivo que permite acceso de lectura/escritura a los archivos que residen en el dispositivo.
+
+Este plugin se basa en varias especificaciones, incluyendo: el HTML5 archivo API
+
+Los directorios (ahora extinto) y sistema de extensiones más recientes: aunque la mayor parte del código del plugin fue escrito cuando una especificación anterior era actual:
+
+También implementa la especificación de FileWriter:
+
+Para el uso, por favor, consulte 'HTML5 Rocks excelente [FileSystem artículo.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+Para tener una visión general de otras opciones de almacenamiento, consulte [Guía de almacenamiento Cordova][2].
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+Este plugin define global `cordova.file` objeto.
+
+Aunque en el ámbito global, no estará disponible hasta después de la `deviceready` evento.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Instalación
+
+ cordova plugin add cordova-plugin-file
+
+
+## Plataformas soportadas
+
+* Amazon fire OS
+* Android
+* BlackBerry 10
+* Firefox OS
+* iOS
+* Windows Phone 7 y 8 *
+* Windows 8 *
+* Explorador
+
+* *No son compatibles con estas plataformas `FileReader.readAsArrayBuffer` ni `FileWriter.write(blob)` .*
+
+## Donde almacenar los archivos
+
+A partir de v1.2.0, URLs a directorios de sistema de archivos importantes son proporcionadas. Cada dirección URL está en la forma *file:///path/to/spot/*y se puede convertir en un `DirectoryEntry` usando`window.resolveLocalFileSystemURL()`.
+
+* `cordova.file.applicationDirectory`-Directorio Read-only donde está instalada la aplicación. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.applicationStorageDirectory`-Directorio del entorno limitado de la aplicación; en iOS esta ubicación es de sólo lectura (pero subdirectorios específicos [como `/Documents` ] son de lectura y escritura). Todos los datos contenidos dentro es privado para la aplicación. ( *iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.dataDirectory`-Almacenamiento de datos persistente y privadas dentro de entorno limitado de la aplicación utilizando la memoria interna (en Android, si necesitas usar memoria externa, use `.externalDataDirectory` ). En iOS, este directorio no está sincronizado con iCloud (utilice `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.cacheDirectory`-Directorio para los archivos de datos almacenados en caché o los archivos que su aplicación puede volver a crear fácilmente. El sistema operativo puede borrar estos archivos cuando el dispositivo se agota en almacenamiento de información, sin embargo, aplicaciones no deben confiar en el sistema operativo para eliminar los archivos de aquí. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-Espacio aplicación de almacenamiento externo. (*Android*)
+
+* `cordova.file.externalDataDirectory`¿Dónde poner los archivos de datos específicos de la aplicación de almacenamiento externo. (*Android*)
+
+* `cordova.file.externalCacheDirectory`-Caché aplicación de almacenamiento externo. (*Android*)
+
+* `cordova.file.externalRootDirectory`-Raíz de almacenamiento externo (tarjeta SD). (*Android*, *BlackBerry 10*)
+
+* `cordova.file.tempDirectory`-Directorio temporal que puede borrar el sistema operativo en sí. No confíe en el sistema operativo para borrar este directorio; su aplicación siempre debe eliminar archivos según corresponda. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-Contiene los archivos de la aplicación específica que deben ser sincronizados (e.g. a iCloud). (*iOS*)
+
+* `cordova.file.documentsDirectory`-Archivos privados a la aplicación, pero que son significativos para otra aplicación (por ejemplo archivos de Office). (*iOS*)
+
+* `cordova.file.sharedDirectory`-Archivos disponibles globalmente para todas las aplicaciones (*BlackBerry 10*)
+
+## Diseños de sistema de archivo
+
+Aunque técnicamente un detalle de la implementación, puede ser muy útil saber cómo la `cordova.file.*` mapa de propiedades en trazados físicos en un dispositivo real.
+
+### iOS diseño de sistema de archivo
+
+| Ruta de dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | sincronización | privado |
+|:-------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:----------:|:--------------:|:-------:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N / A | N / A | N / A | Sí |
+| `appname.app/` | applicationDirectory | Bundle | r | N / A | N / A | N / A | Sí |
+| `www/` | - | - | r | N / A | N / A | N / A | Sí |
+| `Documents/` | documentsDirectory | documentos | r/w | Sí | No | Sí | Sí |
+| `NoCloud/` | - | documentos-nosync | r/w | Sí | No | No | Sí |
+| `Library` | - | Biblioteca | r/w | Sí | No | ¿Sí? | Sí |
+| `NoCloud/` | dataDirectory | Biblioteca-nosync | r/w | Sí | No | No | Sí |
+| `Cloud/` | syncedDataDirectory | - | r/w | Sí | No | Sí | Sí |
+| `Caches/` | cacheDirectory | caché | r/w | Sí * | Si * * *| | No | Sí |
+| `tmp/` | tempDirectory | - | r/w | No * * | Si * * *| | No | Sí |
+
+* Archivos persisten a través de la aplicación se reinicia y actualizaciones, pero este directorio puede ser despejó cuando el OS desea. Su aplicación debe ser capaz de recrear cualquier contenido que puede ser eliminado.
+
+* * Archivos pueden persistir a través de la aplicación se reinicia, pero no confiar en este comportamiento. Los archivos no se garantizan que persisten a través de actualizaciones. Su aplicación debe eliminar los archivos de este directorio cuando es aplicable, como el sistema operativo no garantiza cuando (o incluso si) estos archivos se quitan.
+
+* * *| OS la puede borrar el contenido de este directorio cuando se siente que es necesario, pero no dependen de éste. Debe borrar este directorio según sea apropiado para su aplicación.
+
+### Disposición del sistema Android File
+
+| Ruta de dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | ¿r/w? | ¿persistente? | OS despeja | privado |
+|:----------------------------------------- |:----------------------------------- |:------------------------- |:-----:|:-------------:|:----------:|:-------:|
+| `File:///android_asset/` | applicationDirectory | | r | N / A | N / A | Sí |
+| `/Data/data/< id de aplicación > /` | applicationStorageDirectory | - | r/w | N / A | N / A | Sí |
+| `cache` | cacheDirectory | caché | r/w | Sí | Sí * | Sí |
+| `files` | dataDirectory | archivos | r/w | Sí | No | Sí |
+| `Documents` | | documentos | r/w | Sí | No | Sí |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sí | No | No |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sí | No | No |
+| `cache` | externalCacheDirectry | caché-externo | r/w | Sí | No * * | No |
+| `files` | externalDataDirectory | archivos externos | r/w | Sí | No | No |
+
+* El sistema operativo puede eliminar periódicamente este directorio, pero no dependen de este comportamiento. Borrar el contenido de este directorio según sea apropiado para su aplicación. El contenido de este directorio debe un usuario purga la caché manualmente, se eliminan.
+
+* * El sistema operativo no borra este directorio automáticamente; Usted es responsable de administrar el contenido mismo. Deberá el usuario purga la caché manualmente, se extraen los contenidos del directorio.
+
+**Nota**: Si no se puede montar de almacenamiento externo, el `cordova.file.external*` Propiedades`null`.
+
+### Disposición del sistema blackBerry 10 archivo
+
+| Ruta de dispositivo | `Cordova.file.*` | ¿r/w? | ¿persistente? | OS despeja | privado |
+|:------------------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:----------:|:-------:|
+| `File:///accounts/1000/AppData/ < id de aplicación > /` | applicationStorageDirectory | r | N / A | N / A | Sí |
+| `app/native` | applicationDirectory | r | N / A | N / A | Sí |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sí | Sí |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sí | No | Sí |
+| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sí | No | No |
+| `File:///accounts/1000/shared` | sharedDirectory | r/w | Sí | No | No |
+
+*Nota*: cuando se implementa la aplicación al trabajo de perímetro, todos los caminos son relativos a /accounts/1000-enterprise.
+
+## Rarezas Android
+
+### Ubicación de almacenamiento persistente Android
+
+Hay múltiples ubicaciones válidas para almacenar archivos persistentes en un dispositivo Android. Vea [esta página][3] para una extensa discusión de las distintas posibilidades.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+Las versiones anteriores del plugin elegiría la ubicación de los archivos temporales y persistentes en el arranque, basado en si el dispositivo afirmó que fue montado en la tarjeta SD (o partición de almacenamiento equivalente). Si fue montada en la tarjeta SD, o una partición de gran almacenamiento interno estaba disponible (como en dispositivos de Nexus,) y luego los archivos persistentes se almacenaría en la raíz de ese espacio. Esto significaba que todas las apps Cordova podían ver todos los archivos disponibles en la tarjeta.
+
+Si la tarjeta SD no estaba disponible, entonces versiones anteriores podría almacenar datos debajo de `/data/data/` , que aísla las apps del otro, pero puede todavía causa datos para ser compartido entre los usuarios.
+
+Ahora es posible elegir si desea almacenar archivos en la ubicación de almacenamiento del archivo interno, o usando la lógica anterior, con una preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` :
+
+ < nombre de preferencia = "AndroidPersistentFileLocation" value = "Internal" / >< nombre de preferencia = "AndroidPersistentFileLocation" value = "Compatibilidad" / >
+
+
+Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación.
+
+Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación para "Internal" significa que los usuarios existentes que actualización su aplicación pueden ser incapaces de acceder a sus archivos previamente almacenadas, dependiendo de su dispositivo.
+
+Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Internal` generalmente se recomienda el ajuste.
+
+## iOS rarezas
+
+* `cordova.file.applicationStorageDirectory`es de sólo lectura; intentar almacenar archivos en el directorio raíz fallará. Utilice uno de los `cordova.file.*` las propiedades definidas para iOS (sólo `applicationDirectory` y `applicationStorageDirectory` son de sólo lectura).
+* `FileReader.readAsText(blob, encoding)`
+ * El `encoding` no se admite el parámetro, y codificación UTF-8 es siempre en efecto.
+
+### iOS ubicación de almacenamiento persistente
+
+Hay dos ubicaciones válidas para almacenar archivos persistentes en un dispositivo iOS: el directorio de documentos y el directorio de biblioteca. Las versiones anteriores del plugin sólo almacenan archivos persistentes en el directorio de documentos. Esto tenía el efecto secundario de todos los archivos de la aplicación haciendo visible en iTunes, que era a menudo involuntarios, especialmente para aplicaciones que manejan gran cantidad de archivos pequeños, en lugar de producir documentos completos para la exportación, que es la finalidad del directorio.
+
+Ahora es posible elegir si desea almacenar archivos en los documentos o directorio de bibliotecas, con preferencia en de la aplicación `config.xml` archivo. Para ello, añada una de estas dos líneas a `config.xml` :
+
+
+
+
+
+
+Sin esta línea, se utilizará el archivo plugin `Compatibility` como valor predeterminado. Si una etiqueta de preferencia está presente y no es uno de estos valores, no se iniciará la aplicación.
+
+Si su solicitud se ha enviado previamente a los usuarios, usando un mayor (1.0 pre) versión de este plugin y archivos almacenados en el sistema de ficheros persistente, entonces debería establecer la preferencia en `Compatibility` . Cambiar la ubicación de `Library` significa que los usuarios existentes que actualización su aplicación sería incapaces de acceder a sus archivos previamente almacenadas.
+
+Si su solicitud es nuevo, o nunca antes ha almacenado archivos en el sistema de ficheros persistente, entonces el `Library` generalmente se recomienda el ajuste.
+
+## Firefox OS rarezas
+
+La API de sistema de archivo de forma nativa no es compatible con Firefox OS y se implementa como una cuña en la parte superior indexedDB.
+
+* No falla cuando eliminar directorios no vacía
+* No admite metadatos para directorios
+* Los métodos `copyTo` y `moveTo` no son compatibles con directorios
+
+Se admiten las siguientes rutas de datos: * `applicationDirectory` -usa `xhr` para obtener los archivos locales que están envasados con la aplicación. * `dataDirectory` - Para archivos de datos específicos de aplicación persistente. * `cacheDirectory` -En caché archivos que deben sobrevivir se reinicia la aplicación (aplicaciones no deben confiar en el sistema operativo para eliminar archivos aquí).
+
+## Navegador rarezas
+
+### Rarezas y observaciones comunes
+
+* Cada navegador utiliza su propio sistema de ficheros un espacio aislado. IE y Firefox utilizan IndexedDB como base. Todos los navegadores utilizan diagonal como separador de directorio en un camino.
+* Las entradas de directorio deben crearse sucesivamente. Por ejemplo, la llamada `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` se producirá un error si no existiera dir1.
+* El plugin solicita permiso de usuario para usar almacenamiento persistente en el primer comienzo de la aplicación.
+* Plugin soporta `cdvfile://localhost` (recursos locales) solamente. Es decir, no se admiten los recursos externos vía `cdvfile`.
+* El plugin no sigue ["Archivo sistema API 8.3 nombrando restricciones"][4].
+* BLOB y archivo ' `close` la función no es compatible.
+* `FileSaver` y `BlobBuilder` no son compatibles con este plugin y no tengo recibos.
+* El plugin no es compatible con `requestAllFileSystems`. Esta función también está desaparecida en las especificaciones.
+* No se quitarán las entradas de directorio Si utilizas `create: true` bandera de directorio existente.
+* No se admiten archivos creados mediante el constructor. Debe utilizar método entry.file en su lugar.
+* Cada navegador utiliza su propia forma de blob URL referencias.
+* se admite la función `readAsDataURL`, pero el mediatype en cromo depende de la extensión de nombre de entrada, mediatype en IE siempre está vacío (que es lo mismo como `plain-text` según la especificación), el mediatype en Firefox siempre es `application/octet-stream`. Por ejemplo, si el contenido es `abcdefg` entonces Firefox devuelve `datos: aplicación / octet-stream; base64, YWJjZGVmZw ==`, es decir devuelve `datos:; base64, YWJjZGVmZw ==`, cromo devuelve `datos: < mediatype dependiendo de la extensión de nombre de la entrada >; base64, YWJjZGVmZw ==`.
+* `toInternalURL` devuelve la ruta de la forma `file:///persistent/path/to/entry` (Firefox, IE). Cromo devuelve la ruta de acceso en el formulario `cdvfile://localhost/persistent/file`.
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### Rarezas de Chrome
+
+* Filesystem de Chrome no es inmediatamente después de evento ready dispositivo. Como solución temporal puede suscribirse al evento `filePluginIsReady`. Ejemplo:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+Puede utilizar la función `window.isFilePluginReadyRaised` para verificar si ya se provoca el evento. -window.requestFileSystem temporal y persistente filesystem cuotas no están limitadas en cromo. -Para aumentar el almacenamiento persistente en cromo necesitas llamar el método `window.initPersistentFileSystem`. Cuota de almacenamiento persistente es de 5 MB por defecto. -Chrome requiere `--permitir-archivo-acceso-de-archivos` ejecutar argumento al soporte API mediante protocolo `file:///`. -`Archivo` objeto no cambiará si utilizas bandera `{create:true}` cuando una `entrada` de existente. -eventos `cancelable` propiedad está establecida en true en cromo. Esto es contrario a la [Especificación][5]. -función de `toURL` en Chrome devuelve `filesystem:`-prefijo camino dependiendo de host de la aplicación. Por ejemplo, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -resultado de la función de `toURL` no contiene barra en caso de entrada en el directorio. Cromo resuelve directorios con urls slash-siguió correctamente sin embargo. -método `resolveLocalFileSystemURL` requiere la entrantes `url` que tienen prefijo `filesystem`. Por ejemplo, el parámetro de `url` para `resolveLocalFileSystemURL` debería estar en la forma `filesystem:file:///persistent/somefile.txt` en comparación con la forma `file:///persistent/somefile.txt` en Android. -Obsoleto `toNativeURL` función no es compatible y no tiene un trozo. -función de `setMetadata` no es indicada en las especificaciones y no admite. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de SYNTAX_ERR(code: 8) a petición de un sistema de ficheros inexistentes. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de PATH_EXISTS_ERR(code: 12) en intentar exclusivamente crear un archivo o directorio, que ya existe. -INVALID_MODIFICATION_ERR (código: 9) se lanza en lugar de NO_MODIFICATION_ALLOWED_ERR(code: 6) para tratar de llamar a removeRecursively en el sistema de archivos raíz. -INVALID_MODIFICATION_ERR (código: 9) se lanza en vez de NOT_FOUND_ERR(code: 1) en tratar de moveTo directorio que no existe.
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### Impl base IndexedDB rarezas (IE y Firefox)
+
+* `.` y `..` no son compatibles.
+* IE no soporta `file:///`-modo; modo alojado sólo es compatible (http://localhost:xxxx).
+* Tamaño del sistema de archivos de Firefox no es limitada pero cada extensión de 50 MB solicitará un permiso de usuario. IE10 permite hasta 10mb de combinados AppCache y IndexedDB utilizados en la implementación del sistema de ficheros sin preguntar, cuando llegas a ese nivel que se le preguntará si desea permitir que ser aumentada hasta un máximo de 250 mb por sitio. Para que `size` parámetro para la función `requestFileSystem` no afecta sistema de ficheros en Firefox y IE.
+* la función `readAsBinaryString` no se indica en las especificaciones y no compatible con IE y no tiene un trozo.
+* `file.type` siempre es null.
+* No debe crear entrada utilizando DirectoryEntry resultado de devolución de llamada de instancia que fue borrado. De lo contrario, obtendrá una entrada' colgar'.
+* Antes de que se puede leer un archivo, el cual fue escrito sólo que necesitas una nueva instancia de este archivo.
+* la función `setMetadata`, que no es indicada en las especificaciones soporta sólo el cambio de campo `modificationTime`.
+* `copyTo` y `moveTo` funciones no son compatibles con directorios.
+* Metadatos de directorios no es compatible.
+* Tanto Entry.remove y directoryEntry.removeRecursively no fallan al retirar no vacía directorios - directorios de ser eliminados se limpian junto con contenido en su lugar.
+* `abort` y `truncate` las funciones no son compatibles.
+* eventos de progreso no están despedidos. Por ejemplo, este controlador no ejecutará:
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## Actualización de notas
+
+En v1.0.0 de este plugin, han cambiado las estructuras `FileEntry` y `DirectoryEntry`, para estar más acorde con las especificaciones publicadas.
+
+Versiones anteriores (pre-1.0.0) del plugin almacenan el dispositivo-absoluto-archivo-ubicación en la propiedad `fullPath` de objetos de `entrada`. Estos caminos típicamente parecería
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Estas rutas también fueron devueltos por el método `toURL()` de los objetos de `entrada`.
+
+Con v1.0.0, el atributo `fullPath` es la ruta del archivo, *relativo a la raíz del sistema de archivos HTML*. Así, los caminos más arriba sería ahora ambos ser representado por un objeto `FileEntry` con un `fullPath` de
+
+ /path/to/file
+
+
+Si su aplicación funciona con dispositivo-absoluto-caminos, y previamente obtenido esos caminos a través de la propiedad `fullPath` de objetos de `Entry`, deberá actualizar el código para utilizar `entry.toURL()` en su lugar.
+
+Para atrás compatibilidad, el método `resolveLocalFileSystemURL()` a aceptar un dispositivo-absoluto-trayectoria y devolverá un objeto de `Entry` correspondiente que, mientras exista ese archivo dentro de los sistemas de ficheros `TEMPORARY` o la `PERSISTENT`.
+
+Esto ha sido particularmente un problema con el plugin de transferencia de archivos, que anteriormente utilizado dispositivo-absoluto-caminos (y todavía puede aceptarlas). Ha sido actualizado para funcionar correctamente con sistema de ficheros URLs, para reemplazar `entry.fullPath` con `entry.toURL()` debe resolver cualquier problema conseguir ese plugin para trabajar con archivos en el dispositivo.
+
+En v1.1.0 el valor devuelto por `toURL()` fue cambiado (consulte \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) para devolver una dirección URL absoluta 'file://'. siempre que sea posible. Para asegurar una ' cdvfile:'-URL ahora puede utilizar `toInternalURL()`. Este método devolverá ahora filesystem URLs de la forma
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+que puede utilizarse para identificar el archivo únicamente.
+
+## Lista de códigos de Error y significados
+
+Cuando se produce un error, uno de los siguientes códigos se utilizará.
+
+| Código | Constante |
+| ------:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configurando el Plugin (opcional)
+
+El conjunto de los sistemas de ficheros disponibles puede ser configurado por plataforma. Tanto iOS y Android reconocen un etiqueta en el `archivo config.xml` que nombra a los sistemas de archivos para ser instalado. De forma predeterminada, se activan todas las raíces del sistema de archivos.
+
+
+
+
+
+### Android
+
+* `files`: directorio de almacenamiento de archivo interno de la aplicación
+* `files-external`: directorio de almacenamiento de archivo externo de la aplicación
+* `sdcard`: el directorio de almacenamiento de archivo externo global (esta es la raíz de la tarjeta SD, si uno está instalado). Debe tener el permiso de `android.permission.WRITE_EXTERNAL_STORAGE` a usar esto.
+* `cache`: directorio de memoria caché interna de la aplicación
+* `cache-external`: directorio de caché externo de la aplicación
+* `root`: el sistema de archivos de todo el dispositivo
+
+Android también es compatible con un sistema de archivos especial llamado "documents", que representa un subdirectorio "/Documents/" dentro del sistema de archivos "archivos".
+
+### iOS
+
+* `library`: directorio de bibliotecas de la aplicación
+* `documents`: directorio de documentos de la aplicación
+* `cache`: directorio de caché de la aplicación
+* `bundle`: paquete de la aplicación; la ubicación de la aplicación en sí mismo en el disco (sólo lectura)
+* `root`: el sistema de archivos de todo el dispositivo
+
+De forma predeterminada, los directorios de documentos y la biblioteca pueden ser sincronizados con iCloud. También puede solicitar dos sistemas adicionales, `library-nosync` y `documents-nosync`, que representan un directorio especial no sincronizados dentro de la `/Library` o sistema de ficheros `/Documents`.
diff --git a/plugins/cordova-plugin-file/doc/es/plugins.md b/plugins/cordova-plugin-file/doc/es/plugins.md
new file mode 100644
index 0000000..dace368
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/es/plugins.md
@@ -0,0 +1,101 @@
+
+
+# Notas para los desarrolladores del plugin
+
+Estas notas están pensadas principalmente para desarrolladores de Android y el iOS que quieran escribir plugins que interfaz con el sistema de ficheros usando el plugin del archivo.
+
+## Trabajar con URLs de sistema de archivo de Córdoba
+
+Desde la versión 1.0.0, este plugin ha utilizado las direcciones URL con un `cdvfile` plan para todas las comunicaciones sobre el puente, en lugar de exponer rutas de sistema de archivos de dispositivos raw para JavaScript.
+
+En el lado de JavaScript, esto significa que los objetos FileEntry y DirectoryEntry tienen un atributo fullPath que es relativo a la raíz del sistema de archivos HTML. Si JavaScript API de tu plugin acepta un objeto FileEntry o DirectoryEntry, usted debe llamar a `.toURL()` en ese objeto antes de pasar a través del puente al código nativo.
+
+### Conversión de cdvfile: / / URL al fileystem caminos
+
+Plugins que necesita escribir en el sistema de archivos puede convertir un archivo recibido sistema URL a una ubicación de sistema de archivos real. Hay varias formas de hacerlo, dependiendo de la plataforma nativa.
+
+Es importante recordar que no todos `cdvfile://` las direcciones URL son asignables a reales archivos en el dispositivo. Algunas URLs pueden referirse a activos en dispositivos que no están representadas por archivos, o incluso pueden hacer referencia a recursos remotos. Debido a estas posibilidades, plugins siempre debe comprobar si consiguen un resultado significativo cuando tratando de convertir las URL en trazados.
+
+#### Android
+
+En Android, el método más simple para convertir un `cdvfile://` URL a una ruta de sistema de archivos es utilizar `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`tiene varios métodos que pueden manejar `cdvfile://` URL:
+
+ webView es un miembro de la clase Plugin CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ Obtener una URL file:/// representando este archivo en el dispositivo, / / o el mismo URL sin cambios si no se puede asignar a un archivo Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+También es posible utilizar el plugin de archivos directamente:
+
+ Import org.apache.cordova.file.FileUtils;
+ Import org.apache.cordova.file.FileSystem;
+ Import java.net.MalformedURLException;
+
+ Obtener el archivo plugin desde el administrador de plugin FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ Dada una URL, haz un camino para tratar de {camino de cadena = filePlugin.filesystemPathForURL(cdvfileURL);} catch (DD e) {/ / el sistema de archivos url no reconocida}
+
+
+Para convertir de una ruta a un `cdvfile://` URL:
+
+ Import org.apache.cordova.file.LocalFilesystemURL;
+
+ Obtener un objeto LocalFilesystemURL para una ruta, / / o null si no se puede representar como una dirección URL cdvfile.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ Obtener la representación string de la URL objeto String cdvfileURL = url.toString();
+
+
+Si tu plugin crea un archivo y desea devolver un objeto FileEntry para él, usar el plugin de archivos:
+
+ Devolver una estructura JSON adecuado para volver a JavaScript, / / o null si este archivo no es representable como una dirección URL cdvfile.
+ JSONObject entrada = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+Cordova en iOS no utiliza la misma `CordovaResourceApi` concepto como Android. En iOS, debe usar el archivo plugin para convertir las direcciones URL y rutas de sistema de archivos.
+
+ Obtener un objeto URL CDVFilesystem de una URL string CDVFilesystemURL * url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ Obtener una ruta de acceso para el objeto URL, o nil si no puede ser asignado a una ruta de archivo NSString * = [filePlugin filesystemPathForURL:url];
+
+
+ Obtener un objeto URL CDVFilesystem para una ruta, o / / nula si no se puede representar como una dirección URL cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ Obtener la representación string de la URL objetos NSString * cdvfileURL = [enlace absoluteString];
+
+
+Si tu plugin crea un archivo y desea devolver un objeto FileEntry para él, usar el plugin de archivos:
+
+ Obtener un objeto URL CDVFilesystem para una ruta, o / / nula si no se puede representar como una dirección URL cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ Conseguir una estructura para volver a JavaScript NSDictionary * entrada = [filePlugin makeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+En JavaScript, para obtener un `cdvfile://` dirección URL de un objeto FileEntry o DirectoryEntry, simplemente llame al `.toURL()` en él:
+
+ var cdvfileURL = entry.toURL();
+
+
+En manipuladores de la respuesta del plugin, para convertir de una estructura FileEntry devuelta a un objeto real de la entrada, su código de controlador debe importar el archivo plugin y crear un nuevo objeto:
+
+ crear apropiado objeto var ingreso;
+ Si (entryStruct.isDirectory) {entrada = new DirectoryEntry (entryStruct.name, entryStruct.fullPath, FileSystem(entryStruct.filesystemName)) nuevo;} else {entrada = nuevo FileEntry (entryStruct.name, entryStruct.fullPath, nuevo FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/fr/README.md b/plugins/cordova-plugin-file/doc/fr/README.md
new file mode 100644
index 0000000..6296a84
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/fr/README.md
@@ -0,0 +1,328 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+Ce plugin implémente une API de fichier permettant l'accès en lecture/écriture aux fichiers qui résident sur le périphérique.
+
+Ce plugin est basé sur plusieurs spécifications, y compris : l'API de fichier HTML5
+
+Les répertoires (aujourd'hui disparue) et le système des extensions plus récentes : bien que la plupart du code du plugin a été écrit quand une technique antérieure était en vigueur :
+
+Il met également en œuvre la spécification FileWriter :
+
+Pour son utilisation, veuillez vous reporter au HTML5 Rocks' excellent [article de système de fichiers.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+Pour un aperçu des autres options de stockage, consultez [guide d'entreposage de Cordova](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+Ce plugin définit global `cordova.file` objet.
+
+Bien que dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement.
+
+ document.addEventListener (« deviceready », onDeviceReady, false) ;
+ function onDeviceReady() {console.log(cordova.file);}
+
+
+## Installation
+
+ cordova plugin add cordova-plugin-file
+
+
+## Plates-formes supportées
+
+ * Amazon Fire OS
+ * Android
+ * BlackBerry 10
+ * Firefox OS
+ * iOS
+ * Windows Phone 7 et 8 *
+ * Windows 8 *
+ * Windows*
+ * Navigateur
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## Emplacement de stockage des fichiers
+
+À partir de v1.2.0, URL vers des répertoires de système de fichiers importants est fournis. Chaque URL est dans la forme *file:///path/to/spot/*et peut être converti en un `DirectoryEntry` à l'aide`window.resolveLocalFileSystemURL()`.
+
+ * `cordova.file.applicationDirectory`-Lecture seule répertoire où l'application est installée. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.applicationStorageDirectory`-Répertoire racine du bac à sable de l'application ; cet endroit est en lecture seule sur iOS (mais les sous-répertoires spécifiques [comme `/Documents` ] sont en lecture / écriture). Toutes les données qu'il contient est privé de l'application. ( *iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.dataDirectory`-Stockage des données persistants et privés au sein de bac à sable de l'application à l'aide de la mémoire interne (sur Android, si vous avez besoin d'utiliser une mémoire externe, utilisez `.externalDataDirectory` ). Sur iOS, ce répertoire n'est pas synchronisé avec iCloud (utiliser `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.cacheDirectory`-Répertoire pour les fichiers de données en mémoire cache ou les fichiers que votre application peut recréer facilement. L'OS peut supprimer ces fichiers lorsque l'appareil faiblit sur stockage, néanmoins, les applications ne doivent pas compter sur l'OS pour supprimer les fichiers ici. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-Espace l'application sur le stockage externe. (*Android*)
+
+ * `cordova.file.externalDataDirectory`-Où placer les fichiers de données d'application spécifiques sur le stockage externe. (*Android*)
+
+ * `cordova.file.externalCacheDirectory`-Cache de l'application sur le stockage externe. (*Android*)
+
+ * `cordova.file.externalRootDirectory`-Racine de stockage externe (carte SD). (*Android*, *BlackBerry 10*)
+
+ * `cordova.file.tempDirectory`-Répertoire temp que l'OS peut effacer à volonté. Ne comptez pas sur l'OS pour effacer ce répertoire ; votre application doit toujours supprimer les fichiers selon le cas. (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-Contient des fichiers d'app spécifique qui doivent se synchroniser (par exemple à iCloud). (*iOS*)
+
+ * `cordova.file.documentsDirectory`-Fichiers privés à l'app, mais qui sont significatives pour l'autre application (par exemple les fichiers Office). (*iOS*)
+
+ * `cordova.file.sharedDirectory`-Fichiers disponibles globalement à toutes les applications (*BlackBerry 10*)
+
+## Structures de système de fichiers
+
+Bien que techniquement un détail d'implémentation, il peut être très utile de savoir comment les `cordova.file.*` carte de propriétés à des chemins d'accès physiques sur un périphérique réel.
+
+### iOS agencement de système de fichier
+
+| Chemin de l'unité | `Cordova.file.*` | `iosExtraFileSystems` | r/w ? | persistants ? | OS efface | Sync | privé |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:-------------:|:-----:|:-----:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Oui |
+| `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Oui |
+| `www/` | - | - | r | N/A | N/A | N/A | Oui |
+| `Documents/` | documentsDirectory | documents | r/w | Oui | Non | Oui | Oui |
+| `NoCloud/` | - | documents-nosync | r/w | Oui | Non | Non | Oui |
+| `Library` | - | Bibliothèque | r/w | Oui | Non | Oui ? | Oui |
+| `NoCloud/` | dataDirectory | Bibliothèque-nosync | r/w | Oui | Non | Non | Oui |
+| `Cloud/` | syncedDataDirectory | - | r/w | Oui | Non | Oui | Oui |
+| `Caches/` | cacheDirectory | cache | r/w | Oui * | Oui**\* | Non | Oui |
+| `tmp/` | tempDirectory | - | r/w | Non** | Oui**\* | Non | Oui |
+
+\ * Fichiers persistent à travers l'application redémarre et mises à niveau, mais ce répertoire peut être effacé à chaque fois que le système d'exploitation désire. Votre application doit être en mesure de recréer tout contenu qui pourrait être supprimé.
+
+** Fichiers peuvent persister redémarrages de l'application, mais ne vous fiez pas ce comportement. Les fichiers ne sont pas garantis à persister dans l'ensemble de mises à jour. Votre application doit supprimer les fichiers de ce répertoire lorsqu'elle s'applique, comme le système d'exploitation ne garantit pas quand (ou même si) ces fichiers sont supprimés.
+
+**\ * Le système d'exploitation peut effacer le contenu de ce répertoire chaque fois qu'il se sent il est nécessaire, mais ne comptez pas là-dessus. Vous devez supprimer ce répertoire comme approprié pour votre application.
+
+### Agencement de système de fichiers Android
+
+| Chemin de l'unité | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w ? | persistants ? | OS efface | privé |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:-----:|:-------------:|:---------:|:-----:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Oui |
+| `/ données/data/app < id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | Oui |
+| `cache` | cacheDirectory | cache | r/w | Oui | Oui\ * | Oui |
+| `files` | dataDirectory | fichiers | r/w | Oui | Non | Oui |
+| `Documents` | | documents | r/w | Oui | Non | Oui |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Oui | Non | Non |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Oui | Non | Non |
+| `cache` | externalCacheDirectry | cache-externe | r/w | Oui | Non** | Non |
+| `files` | externalDataDirectory | fichiers externes | r/w | Oui | Non | Non |
+
+\ * L'OS peut effacer périodiquement ce répertoire, mais ne vous fiez pas ce comportement. Effacer le contenu de ce répertoire comme approprié pour votre application. Un utilisateur doit purger le cache manuellement, le contenu de ce répertoire est supprimé.
+
+** Le système d'exploitation n'efface pas ce répertoire automatiquement ; vous êtes chargé de gérer le contenu vous-même. L'utilisateur devrait purger le cache manuellement, le contenu du répertoire est supprimé.
+
+**Remarque**: si le stockage externe ne peut pas être monté, les `cordova.file.external*` sont des propriétés`null`.
+
+### Configuration du système blackBerry 10 fichier
+
+| Chemin de l'unité | `Cordova.file.*` | r/w ? | persistants ? | OS efface | privé |
+|:----------------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:---------:|:-----:|
+| `file:///Accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Oui |
+| `app/native` | applicationDirectory | r | N/A | N/A | Oui |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Non | Oui | Oui |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Oui | Non | Oui |
+| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Oui | Non | Non |
+| `file:///Accounts/1000/Shared` | sharedDirectory | r/w | Oui | Non | Non |
+
+*Remarque*: lorsque l'application est déployée dans le périmètre de travail, tous les chemins sont par rapport à /accounts/1000-enterprise.
+
+## Quirks Android
+
+### Emplacement de stockage persistant Android
+
+Il y a plusieurs emplacements valides pour stocker des fichiers persistants sur un appareil Android. Voir [cette page](http://developer.android.com/guide/topics/data/data-storage.html) pour une analyse approfondie des diverses possibilités.
+
+Les versions précédentes du plugin choisirait l'emplacement des fichiers temporaires et persistantes au démarrage, basé sur la question de savoir si le dispositif réclamé que la carte SD (ou une partition de stockage équivalent) a été montée. Si la carte SD a été montée, ou si une partition de stockage interne importante était disponible (comme sur les appareils Nexus,) puis les fichiers persistants seraient stockés dans la racine de cet espace. Cela signifie que toutes les apps de Cordova pouvaient voir tous les fichiers disponibles sur la carte.
+
+Si la carte SD n'était pas disponible, les versions précédentes pourraient stocker des données sous `/data/data/` , qui isole des apps de l'autre, mais peut encore cause données à partager entre les utilisateurs.
+
+Il est maintenant possible de choisir de stocker les fichiers dans l'emplacement de stockage de fichier interne, ou en utilisant la logique précédente, avec une préférence au sein de votre application `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` :
+
+ < nom de l'option = « AndroidPersistentFileLocation » value = « Internal » / >< nom de préférence = « AndroidPersistentFileLocation » value = « Compatibilité » / >
+
+
+Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas.
+
+Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Commutation de l'emplacement « Internal » signifierait que les utilisateurs existants qui mettre à niveau leur application peuvent être impossible d'accéder à leurs fichiers déjà enregistrés, selon leur appareil.
+
+Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Internal` réglage est généralement recommandé.
+
+### Opérations récursives lent pour /android_asset
+
+Liste des répertoires actifs est vraiment lent sur Android. Vous pouvez accélérer il vers le haut, en ajoutant `src/android/build-extras.gradle` à la racine de votre projet android (requiert également cordova-android@4.0.0 ou supérieur).
+
+## Notes au sujet d'iOS
+
+ * `cordova.file.applicationStorageDirectory`est en lecture seule ; tentative de stocker des fichiers dans le répertoire racine échoue. Utilisez l'une de l'autre `cordova.file.*` les propriétés définies pour iOS (seulement `applicationDirectory` et `applicationStorageDirectory` sont en lecture seule).
+ * `FileReader.readAsText(blob, encoding)`
+ * Le `encoding` paramètre n'est pas pris en charge, et le codage UTF-8 est toujours en vigueur.
+
+### emplacement de stockage persistant d'iOS
+
+Il y a deux emplacements valides pour stocker des fichiers persistants sur un appareil iOS : le répertoire de Documents et le répertoire de la bibliothèque. Les versions précédentes du plugin stockaient ne jamais fichiers persistants dans le répertoire de Documents. Cela a eu l'effet secondaire de rendre tous les fichiers de l'application visible dans iTunes, qui était souvent inattendus, en particulier pour les applications qui traitent beaucoup de petits fichiers, plutôt que de produire des documents complets destinés à l'exportation, qui est l'objectif visé par le répertoire.
+
+Il est maintenant possible de choisir de stocker les fichiers dans le répertoire de bibliothèque, avec une préférence au sein de votre application ou de documents `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` :
+
+ < nom de l'option = « iosPersistentFileLocation » value = « Library » / >< nom de préférence = « iosPersistentFileLocation » value = « Compatibilité » / >
+
+
+Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas.
+
+Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Changer l'emplacement de `Library` voudrait dire que les utilisateurs existants qui mettre à niveau leur application serait incapables d'accéder à leurs fichiers déjà enregistrés.
+
+Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Library` réglage est généralement recommandé.
+
+## Firefox OS Quirks
+
+L'API de système de fichier n'est pas nativement pris en charge par Firefox OS et est implémentée comme une cale d'épaisseur sur le dessus d'indexedDB.
+
+ * Ne manque pas lors de la suppression des répertoires non vide
+ * Ne supporte pas les métadonnées pour les répertoires
+ * Méthodes `copyTo` et `moveTo` ne prennent pas en charge les répertoires
+
+Les chemins de données suivants sont pris en charge: * `applicationDirectory` -utilise `xhr` pour obtenir des fichiers les qui sont emballées avec l'app. * `dataDirectory` - Pour les fichiers de données persistantes de app spécifique. * `cacheDirectory` -Mise en cache de fichiers qui doivent survivre les redémarrages de l'application (les applications ne doivent pas compter sur le système d'exploitation pour supprimer les fichiers ici).
+
+## Bizarreries navigateur
+
+### Commune de bizarreries et de remarques
+
+ * Chaque navigateur utilise son propre système de fichiers en bac à sable. IE et Firefox utilisent IndexedDB comme base. Tous les navigateurs utilisent oblique comme séparateur de répertoire dans un chemin d'accès.
+ * Entrées d'annuaire doivent être créées successivement. Par exemple, l'appel `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` échouera si dir1 n'existait pas.
+ * Le plugin demande utilisateur l'autorisation d'utiliser le stockage persistant lors du premier démarrage d'application.
+ * Plugin supporte `cdvfile://localhost` (ressources locales) seulement. C'est-à-dire les ressources externes ne sont pas supportés par l'intermédiaire de `cdvfile`.
+ * Le plugin ne suit pas les ["Restrictions de nommage des fichiers système API 8.3"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
+ * BLOB et le fichier "`close` la fonction n'est pas pris en charge.
+ * `FileSaver` et `BlobBuilder` ne sont pas pris en charge par ce plugin et n'ont stubs.
+ * Le plugin ne supporte pas les `requestAllFileSystems`. Cette fonction est également absent dans les cahier des charges.
+ * Inscriptions dans l'annuaire ne seront pas supprimées si vous utilisez `create: true` drapeau pour le répertoire existant.
+ * Fichiers créés via le constructeur ne sont pas pris en charge. Vous devez plutôt utiliser entry.file méthode.
+ * Chaque navigateur utilise sa propre forme de références URL blob.
+ * `readAsDataURL` fonction est prise en charge, mais le mediatype en Chrome dépend de l'extension entrée, mediatype dans IE est toujours vide (qui est le même que le `texte-plaine` selon la spécification), le mediatype dans Firefox est toujours `application/octet-stream`. Par exemple, si le contenu est `abcdefg` puis Firefox renvoie `données : application / octet-stream ; base64, YWJjZGVmZw ==`, c'est à dire les retours `données:; base64, YWJjZGVmZw ==`, retours de Chrome `données : < mediatype selon l'extension de nom d'entrée > ; base64, YWJjZGVmZw ==`.
+ * `toInternalURL` retourne le chemin d'accès dans le formulaire `file:///persistent/path/to/entry` (Firefox, IE). Chrome retourne le chemin d'accès dans le formulaire `cdvfile://localhost/persistent/file`.
+
+### Bizarreries de chrome
+
+ * Chrome filesystem n'est pas prête immédiatement après l'événement ready périphérique. Pour contourner le problème, vous pouvez vous abonner à l'événement `filePluginIsReady`. Exemple :
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+Vous pouvez utiliser la fonction `window.isFilePluginReadyRaised` pour vérifier si les événement était déjà déclenché. -quotas de window.requestFileSystem temporaire et permanent de système de fichiers ne sont pas limités en Chrome. -Pour augmenter le stockage persistant en Chrome, vous devez appeler la méthode `window.initPersistentFileSystem`. Quota de stockage persistant est 5 Mo par défaut. -Chrome nécessite `--permettre-fichier-accès-de-fichiers` exécuter l'argument au support API via le protocole `file:///`. -`Fichier` objet changera pas si vous utilisez le drapeau `{create:true}` lors du passage d'une `entrée` existante. -événements `annulables` propriété a la valeur true dans Chrome. Il s'agit à l'encontre de la [spécification](http://dev.w3.org/2009/dap/file-system/file-writer.html). -`toURL` renvoie à Chrome `système de fichiers :`-préfixe de chemin d'accès selon l'application hôte. Par exemple, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -résultat de la fonction `toURL` ne contient-elle pas de barre oblique dans le cas d'entrée d'annuaire. Chrome résout répertoires avec barre oblique-trainés URL correctement cependant. -`resolveLocalFileSystemURL` méthode nécessite l' entrant `url` préfixe de `système de fichiers`. Par exemple, le paramètre `d'url` pour `resolveLocalFileSystemURL` devrait être dans la forme `filesystem:file:///persistent/somefile.txt` par opposition à la forme `file:///persistent/somefile.txt` dans Android. -Déconseillée `toNativeURL` fonction n'est pas prise en charge et n'est pas une ébauche. -fonction de `setMetadata` n'est pas stipulée dans le devis et pas pris en charge. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de SYNTAX_ERR(code: 8) sur la demande d'un système de fichier inexistant. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de PATH_EXISTS_ERR(code: 12) à essayer de créer exclusivement un fichier ou un répertoire, qui existe déjà. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NO_MODIFICATION_ALLOWED_ERR(code: 6) à essayer d'appeler removeRecursively sur le système de fichiers racine. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NOT_FOUND_ERR(code: 1) en essayant de moveTo répertoire qui n'existe pas.
+
+### Base IndexedDB impl bizarreries (Firefox et IE)
+
+ * `.` et `.` ne sont pas pris en charge.
+ * IE ne prend pas en charge les `file:///`-mode ; seul le mode hébergé est pris en charge (http://localhost:xxxx).
+ * Taille de système de fichiers de Firefox n'est pas limité, mais chaque extension de 50Mo demandera une autorisation de l'utilisateur. IE10 permet jusqu'à 10 Mo de combiné AppCache et IndexedDB utilisés dans la mise en œuvre du système de fichiers sans demander de confirmation, une fois que vous atteignez ce niveau, Qu'on vous demandera si vous souhaitez lui permettre d'être augmentée jusqu'à un maximum de 250 Mo par site. Si le paramètre de `taille` pour la fonction `requestFileSystem` n'affecte pas le système de fichiers dans Firefox et IE.
+ * fonction de `readAsBinaryString` n'est pas indiquée dans les spécifications et pas pris en charge dans Internet Explorer et n'a pas une ébauche.
+ * `file.type` est toujours null.
+ * Vous ne devez pas créer en utilisant le résultat du callback instance DirectoryEntry qui avait été supprimée. Sinon, vous obtiendrez une « entrée de pendaison ».
+ * Avant que vous pouvez lire un fichier qui a été écrit juste que vous devez obtenir une nouvelle instance de ce fichier.
+ * `setMetadata` fonction, qui n'est pas indiquée dans les spécifications supporte `modificationTime` changement de champ seulement.
+ * fonctions `copyTo` et `moveTo` ne supportent pas les répertoires.
+ * Répertoires métadonnées ne sont pas pris en charge.
+ * Les deux Entry.remove et directoryEntry.removeRecursively ne manquent pas lors de la suppression des répertoires non-vides - répertoires retirés sont nettoyés avec contenu au lieu de cela.
+ * fonctions `abort` et `truncate` ne sont pas supportées.
+ * événements de progression ne sont pas déclenchés. Par exemple, ce gestionnaire ne sera pas exécuté :
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## Notes de mise à niveau
+
+V1.0.0 de ce plugin, les structures `FileEntry` et `DirectoryEntry` ont changé, pour être plus conforme à la spécification publiée.
+
+Les versions précédentes de (pré-1.0.0) du plugin stockaient le dispositif-absolu--emplacement du fichier dans la propriété `fullPath` d'objets `d'entrée`. Ces chemins seraient présente généralement comme
+
+ / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android)
+
+
+Ces chemins ont été également retournés par la méthode de `toURL()` les objets `d'entrée`.
+
+Avec v1.0.0, l'attribut `fullPath` est le chemin d'accès au fichier, *par rapport à la racine du système de fichiers HTML*. Ainsi, les chemins d'accès ci-dessus seraient maintenant tous les deux être représentée par un objet `FileEntry` avec un `fullPath` de
+
+ /path/to/file
+
+
+Si votre application fonctionne avec le dispositif-absolu-chemins et que vous avez récupéré précédemment ces chemins d'accès par le biais de la propriété `fullPath` d'objets `d'entrée`, puis vous devez mettre à jour votre code afin d'utiliser `entry.toURL()` à la place.
+
+Pour vers l'arrière la compatibilité, la méthode `resolveLocalFileSystemURL()` sera un chemin absolu de l'unité et retourne un objet `Entry` correspondant à elle, tant que ce fichier existe au sein des systèmes de fichiers les `TEMPORARY` ou `PERSISTENT`.
+
+Cela a été particulièrement un problème avec le plugin de transfert de fichiers, qui autrefois périphérique-absolu-chemins (et peut encore accepter). Il a été mis à jour pour fonctionner correctement avec le système de fichiers URL, afin de remplacer `entry.fullPath` par `entry.toURL()` devrait résoudre tout problème obtenir ce plugin pour travailler avec des fichiers sur le périphérique.
+
+Dans v1.1.0 la valeur de retour de `toURL()` a été changée (voir \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) pour renvoyer une URL absolue "file://". dans la mesure du possible. Pour assurer un ' cdvfile:'-URL, vous pouvez utiliser `toInternalURL()` maintenant. Cette méthode retourne maintenant filesystem URL du formulaire
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+qui peut servir à identifier de manière unique le fichier.
+
+## Liste des Codes d'erreur et leur signification
+
+Lorsqu'une erreur est levée, l'un des codes suivants sera utilisé.
+
+| Code | Constant |
+| ----:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configuration du Plugin (facultatif)
+
+L'ensemble des systèmes de fichiers disponibles peut être configurée par plate-forme. Les iOS et Android reconnaissent une balise dans le `fichier config.xml` qui nomme les systèmes de fichiers à installer. Par défaut, toutes les racines du système de fichiers sont activées.
+
+
+
+
+
+### Android
+
+ * `files` : répertoire de stockage de fichier interne de l'application
+ * `files-external` : répertoire de l'application de stockage de fichier externe
+ * `sdcard` : le répertoire de stockage global fichier externe (c'est la racine de la carte SD, s'il est installé). Vous devez avoir la permission de `android.permission.WRITE_EXTERNAL_STORAGE` de l'utiliser.
+ * `cache` : répertoire de cache interne de l'application
+ * `cache-external` : répertoire de cache externe de l'application
+ * `root` : le système de fichiers de tout dispositif
+
+Android prend également en charge un système de fichiers spécial nommé « documents », qui représente un sous-répertoire « / Documents / » dans le système de fichiers « files ».
+
+### iOS
+
+ * `library` : répertoire de bibliothèque de l'application
+ * `documents` : répertoire de Documents de l'application
+ * `cache` : répertoire de Cache de l'application
+ * `bundle` : bundle de l'application ; l'emplacement de l'application elle-même sur disque (lecture seule)
+ * `root` : le système de fichiers de tout dispositif
+
+Par défaut, vous peuvent synchroniser les répertoires de la bibliothèque et les documents à iCloud. Vous pouvez également demander des deux systèmes de fichiers supplémentaires, `library-nosync` et `documents-nosync`, qui représentent un répertoire spécial non synchronisées dans le `/Library` ou système de fichiers `/ Documents`.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/fr/index.md b/plugins/cordova-plugin-file/doc/fr/index.md
new file mode 100644
index 0000000..7235522
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/fr/index.md
@@ -0,0 +1,331 @@
+
+
+# cordova-plugin-file
+
+Ce plugin implémente une API de fichier permettant l'accès en lecture/écriture aux fichiers qui résident sur le périphérique.
+
+Ce plugin est basé sur plusieurs spécifications, y compris : l'API de fichier HTML5
+
+Les répertoires (aujourd'hui disparue) et le système des extensions plus récentes : bien que la plupart du code du plugin a été écrit quand une technique antérieure était en vigueur :
+
+Il met également en œuvre la spécification FileWriter :
+
+Pour son utilisation, veuillez vous reporter au HTML5 Rocks' excellent [article de système de fichiers.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+Pour un aperçu des autres options de stockage, consultez [guide d'entreposage de Cordova][2].
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+Ce plugin définit global `cordova.file` objet.
+
+Bien que dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement.
+
+ document.addEventListener (« deviceready », onDeviceReady, false) ;
+ function onDeviceReady() {console.log(cordova.file);}
+
+
+## Installation
+
+ Cordova plugin ajouter cordova-plugin-file
+
+
+## Plates-formes prises en charge
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Firefox OS
+* iOS
+* Windows Phone 7 et 8 *
+* Windows 8 *
+* Navigateur
+
+* *Ces plates-formes ne supportent pas `FileReader.readAsArrayBuffer` ni `FileWriter.write(blob)` .*
+
+## Emplacement de stockage des fichiers
+
+À partir de v1.2.0, URL vers des répertoires de système de fichiers importants est fournis. Chaque URL est dans la forme *file:///path/to/spot/*et peut être converti en un `DirectoryEntry` à l'aide`window.resolveLocalFileSystemURL()`.
+
+* `cordova.file.applicationDirectory`-Lecture seule répertoire où l'application est installée. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.applicationStorageDirectory`-Répertoire racine du bac à sable de l'application ; cet endroit est en lecture seule sur iOS (mais les sous-répertoires spécifiques [comme `/Documents` ] sont en lecture / écriture). Toutes les données qu'il contient est privé de l'application. ( *iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.dataDirectory`-Stockage des données persistants et privés au sein de bac à sable de l'application à l'aide de la mémoire interne (sur Android, si vous avez besoin d'utiliser une mémoire externe, utilisez `.externalDataDirectory` ). Sur iOS, ce répertoire n'est pas synchronisé avec iCloud (utiliser `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.cacheDirectory`-Répertoire pour les fichiers de données en mémoire cache ou les fichiers que votre application peut recréer facilement. L'OS peut supprimer ces fichiers lorsque l'appareil faiblit sur stockage, néanmoins, les applications ne doivent pas compter sur l'OS pour supprimer les fichiers ici. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-Espace l'application sur le stockage externe. (*Android*)
+
+* `cordova.file.externalDataDirectory`-Où placer les fichiers de données d'application spécifiques sur le stockage externe. (*Android*)
+
+* `cordova.file.externalCacheDirectory`-Cache de l'application sur le stockage externe. (*Android*)
+
+* `cordova.file.externalRootDirectory`-Racine de stockage externe (carte SD). (*Android*, *BlackBerry 10*)
+
+* `cordova.file.tempDirectory`-Répertoire temp que l'OS peut effacer à volonté. Ne comptez pas sur l'OS pour effacer ce répertoire ; votre application doit toujours supprimer les fichiers selon le cas. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-Contient des fichiers d'app spécifique qui doivent se synchroniser (par exemple à iCloud). (*iOS*)
+
+* `cordova.file.documentsDirectory`-Fichiers privés à l'app, mais qui sont significatives pour l'autre application (par exemple les fichiers Office). (*iOS*)
+
+* `cordova.file.sharedDirectory`-Fichiers disponibles globalement à toutes les applications (*BlackBerry 10*)
+
+## Structures de système de fichiers
+
+Bien que techniquement un détail d'implémentation, il peut être très utile de savoir comment les `cordova.file.*` carte de propriétés à des chemins d'accès physiques sur un périphérique réel.
+
+### iOS agencement de système de fichier
+
+| Chemin de l'unité | `Cordova.file.*` | `iosExtraFileSystems` | r/w ? | persistants ? | OS efface | Sync | privé |
+|:-------------------------------------------- |:--------------------------- |:--------------------- |:-----:|:-------------:|:-----------:|:-----:|:-----:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Oui |
+| `appname.app/` | applicationDirectory | Bundle | r | N/A | N/A | N/A | Oui |
+| `www/` | - | - | r | N/A | N/A | N/A | Oui |
+| `Documents/` | documentsDirectory | documents | r/w | Oui | Non | Oui | Oui |
+| `NoCloud/` | - | documents-nosync | r/w | Oui | Non | Non | Oui |
+| `Library` | - | Bibliothèque | r/w | Oui | Non | Oui ? | Oui |
+| `NoCloud/` | dataDirectory | Bibliothèque-nosync | r/w | Oui | Non | Non | Oui |
+| `Cloud/` | syncedDataDirectory | - | r/w | Oui | Non | Oui | Oui |
+| `Caches/` | cacheDirectory | cache | r/w | Oui * | Oui * * *| | Non | Oui |
+| `tmp/` | tempDirectory | - | r/w | Ne * * | Oui * * *| | Non | Oui |
+
+* Fichiers persistent à travers les redémarrages de l'application et mises à niveau, mais ce répertoire peut être effacé à chaque fois que les désirs de l'OS. Votre application doit être en mesure de recréer tout contenu qui pourrait être supprimé.
+
+* * Fichiers peuvent persister redémarrages de l'application, mais ne vous fiez pas ce comportement. Les fichiers ne sont pas garantis à persister dans l'ensemble de mises à jour. Votre application doit supprimer les fichiers de ce répertoire lorsqu'elle s'applique, comme le système d'exploitation ne garantit pas quand (ou même si) ces fichiers sont supprimés.
+
+* * *| L'OS peut effacer le contenu de ce répertoire chaque fois qu'il se sent il est nécessaire, mais ne comptez pas là-dessus. Vous devez supprimer ce répertoire comme approprié pour votre application.
+
+### Agencement de système de fichiers Android
+
+| Chemin de l'unité | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w ? | persistants ? | OS efface | privé |
+|:----------------------------------- |:----------------------------------- |:------------------------- |:-----:|:-------------:|:---------:|:-----:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Oui |
+| `/ données/data/app < id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | Oui |
+| `cache` | cacheDirectory | cache | r/w | Oui | Oui * | Oui |
+| `files` | dataDirectory | fichiers | r/w | Oui | Non | Oui |
+| `Documents` | | documents | r/w | Oui | Non | Oui |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Oui | Non | Non |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Oui | Non | Non |
+| `cache` | externalCacheDirectry | cache-externe | r/w | Oui | Ne * * | Non |
+| `files` | externalDataDirectory | fichiers externes | r/w | Oui | Non | Non |
+
+* Le système d'exploitation peut effacer périodiquement ce répertoire, mais ne vous fiez pas ce comportement. Effacer le contenu de ce répertoire comme approprié pour votre application. Un utilisateur doit purger le cache manuellement, le contenu de ce répertoire est supprimé.
+
+* * The OS vous n'effacez pas ce répertoire automatiquement ; vous êtes chargé de gérer le contenu vous-même. L'utilisateur devrait purger le cache manuellement, le contenu du répertoire est supprimé.
+
+**Remarque**: si le stockage externe ne peut pas être monté, les `cordova.file.external*` sont des propriétés`null`.
+
+### Configuration du système blackBerry 10 fichier
+
+| Chemin de l'unité | `Cordova.file.*` | r/w ? | persistants ? | OS efface | privé |
+|:--------------------------------------------------- |:--------------------------- |:-----:|:-------------:|:---------:|:-----:|
+| `file:///Accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Oui |
+| `app/native` | applicationDirectory | r | N/A | N/A | Oui |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Non | Oui | Oui |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Oui | Non | Oui |
+| `file:///Accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Oui | Non | Non |
+| `file:///Accounts/1000/Shared` | sharedDirectory | r/w | Oui | Non | Non |
+
+*Remarque*: lorsque l'application est déployée dans le périmètre de travail, tous les chemins sont par rapport à /accounts/1000-enterprise.
+
+## Quirks Android
+
+### Emplacement de stockage persistant Android
+
+Il y a plusieurs emplacements valides pour stocker des fichiers persistants sur un appareil Android. Voir [cette page][3] pour une analyse approfondie des diverses possibilités.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+Les versions précédentes du plugin choisirait l'emplacement des fichiers temporaires et persistantes au démarrage, basé sur la question de savoir si le dispositif réclamé que la carte SD (ou une partition de stockage équivalent) a été montée. Si la carte SD a été montée, ou si une partition de stockage interne importante était disponible (comme sur les appareils Nexus,) puis les fichiers persistants seraient stockés dans la racine de cet espace. Cela signifie que toutes les apps de Cordova pouvaient voir tous les fichiers disponibles sur la carte.
+
+Si la carte SD n'était pas disponible, les versions précédentes pourraient stocker des données sous `/data/data/` , qui isole des apps de l'autre, mais peut encore cause données à partager entre les utilisateurs.
+
+Il est maintenant possible de choisir de stocker les fichiers dans l'emplacement de stockage de fichier interne, ou en utilisant la logique précédente, avec une préférence au sein de votre application `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` :
+
+ < nom de l'option = « AndroidPersistentFileLocation » value = « Internal » / >< nom de préférence = « AndroidPersistentFileLocation » value = « Compatibilité » / >
+
+
+Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas.
+
+Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Commutation de l'emplacement « Internal » signifierait que les utilisateurs existants qui mettre à niveau leur application peuvent être impossible d'accéder à leurs fichiers déjà enregistrés, selon leur appareil.
+
+Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Internal` réglage est généralement recommandé.
+
+## iOS Quirks
+
+* `cordova.file.applicationStorageDirectory`est en lecture seule ; tentative de stocker des fichiers dans le répertoire racine échoue. Utilisez l'une de l'autre `cordova.file.*` les propriétés définies pour iOS (seulement `applicationDirectory` et `applicationStorageDirectory` sont en lecture seule).
+* `FileReader.readAsText(blob, encoding)`
+ * Le `encoding` paramètre n'est pas pris en charge, et le codage UTF-8 est toujours en vigueur.
+
+### emplacement de stockage persistant d'iOS
+
+Il y a deux emplacements valides pour stocker des fichiers persistants sur un appareil iOS : le répertoire de Documents et le répertoire de la bibliothèque. Les versions précédentes du plugin stockaient ne jamais fichiers persistants dans le répertoire de Documents. Cela a eu l'effet secondaire de rendre tous les fichiers de l'application visible dans iTunes, qui était souvent inattendus, en particulier pour les applications qui traitent beaucoup de petits fichiers, plutôt que de produire des documents complets destinés à l'exportation, qui est l'objectif visé par le répertoire.
+
+Il est maintenant possible de choisir de stocker les fichiers dans le répertoire de bibliothèque, avec une préférence au sein de votre application ou de documents `config.xml` fichier. Pour ce faire, ajoutez l'un de ces deux lignes de `config.xml` :
+
+ < nom de l'option = « iosPersistentFileLocation » value = « Library » / >< nom de préférence = « iosPersistentFileLocation » value = « Compatibilité » / >
+
+
+Sans cette ligne, utilisera le fichier plugin `Compatibility` par défaut. Si une balise de préférence est présente et n'est pas une des valeurs suivantes, l'application ne démarrera pas.
+
+Si votre application a déjà été expédiée aux utilisateurs, en utilisant une ancienne (avant 1.0) version de ce plugin et dispose des fichiers stockés dans le système de fichiers persistant, alors vous devez définir la préférence au `Compatibility` . Changer l'emplacement de `Library` voudrait dire que les utilisateurs existants qui mettre à niveau leur application serait incapables d'accéder à leurs fichiers déjà enregistrés.
+
+Si votre application est nouvelle ou a jamais précédemment stocké les fichiers dans le système de fichiers persistant, puis la `Library` réglage est généralement recommandé.
+
+## Firefox OS Quirks
+
+L'API de système de fichier n'est pas nativement pris en charge par Firefox OS et est implémentée comme une cale d'épaisseur sur le dessus d'indexedDB.
+
+* Ne manque pas lors de la suppression des répertoires non vide
+* Ne supporte pas les métadonnées pour les répertoires
+* Méthodes `copyTo` et `moveTo` ne prennent pas en charge les répertoires
+
+Les chemins de données suivants sont pris en charge: * `applicationDirectory` -utilise `xhr` pour obtenir des fichiers les qui sont emballées avec l'app. * `dataDirectory` - Pour les fichiers de données persistantes de app spécifique. * `cacheDirectory` -Mise en cache de fichiers qui doivent survivre les redémarrages de l'application (les applications ne doivent pas compter sur le système d'exploitation pour supprimer les fichiers ici).
+
+## Bizarreries navigateur
+
+### Commune de bizarreries et de remarques
+
+* Chaque navigateur utilise son propre système de fichiers en bac à sable. IE et Firefox utilisent IndexedDB comme base. Tous les navigateurs utilisent oblique comme séparateur de répertoire dans un chemin d'accès.
+* Entrées d'annuaire doivent être créées successivement. Par exemple, l'appel `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` échouera si dir1 n'existait pas.
+* Le plugin demande utilisateur l'autorisation d'utiliser le stockage persistant lors du premier démarrage d'application.
+* Plugin supporte `cdvfile://localhost` (ressources locales) seulement. C'est-à-dire les ressources externes ne sont pas supportés par l'intermédiaire de `cdvfile`.
+* Le plugin ne suit pas les ["Restrictions de nommage des fichiers système API 8.3"][4].
+* BLOB et le fichier "`close` la fonction n'est pas pris en charge.
+* `FileSaver` et `BlobBuilder` ne sont pas pris en charge par ce plugin et n'ont stubs.
+* Le plugin ne supporte pas les `requestAllFileSystems`. Cette fonction est également absent dans les cahier des charges.
+* Inscriptions dans l'annuaire ne seront pas supprimées si vous utilisez `create: true` drapeau pour le répertoire existant.
+* Fichiers créés via le constructeur ne sont pas pris en charge. Vous devez plutôt utiliser entry.file méthode.
+* Chaque navigateur utilise sa propre forme de références URL blob.
+* `readAsDataURL` fonction est prise en charge, mais le mediatype en Chrome dépend de l'extension entrée, mediatype dans IE est toujours vide (qui est le même que le `texte-plaine` selon la spécification), le mediatype dans Firefox est toujours `application/octet-stream`. Par exemple, si le contenu est `abcdefg` puis Firefox renvoie `données : application / octet-stream ; base64, YWJjZGVmZw ==`, c'est à dire les retours `données:; base64, YWJjZGVmZw ==`, retours de Chrome `données : < mediatype selon l'extension de nom d'entrée > ; base64, YWJjZGVmZw ==`.
+* `toInternalURL` retourne le chemin d'accès dans le formulaire `file:///persistent/path/to/entry` (Firefox, IE). Chrome retourne le chemin d'accès dans le formulaire `cdvfile://localhost/persistent/file`.
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### Bizarreries de chrome
+
+* Chrome filesystem n'est pas prête immédiatement après l'événement ready périphérique. Pour contourner le problème, vous pouvez vous abonner à l'événement `filePluginIsReady`. Exemple :
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+Vous pouvez utiliser la fonction `window.isFilePluginReadyRaised` pour vérifier si les événement était déjà déclenché. -quotas de window.requestFileSystem temporaire et permanent de système de fichiers ne sont pas limités en Chrome. -Pour augmenter le stockage persistant en Chrome, vous devez appeler la méthode `window.initPersistentFileSystem`. Quota de stockage persistant est 5 Mo par défaut. -Chrome nécessite `--permettre-fichier-accès-de-fichiers` exécuter l'argument au support API via le protocole `file:///`. -`Fichier` objet changera pas si vous utilisez le drapeau `{create:true}` lors du passage d'une `entrée` existante. -événements `annulables` propriété a la valeur true dans Chrome. Il s'agit à l'encontre de la [spécification][5]. -`toURL` renvoie à Chrome `système de fichiers :`-préfixe de chemin d'accès selon l'application hôte. Par exemple, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -résultat de la fonction `toURL` ne contient-elle pas de barre oblique dans le cas d'entrée d'annuaire. Chrome résout répertoires avec barre oblique-trainés URL correctement cependant. -`resolveLocalFileSystemURL` méthode nécessite l' entrant `url` préfixe de `système de fichiers`. Par exemple, le paramètre `d'url` pour `resolveLocalFileSystemURL` devrait être dans la forme `filesystem:file:///persistent/somefile.txt` par opposition à la forme `file:///persistent/somefile.txt` dans Android. -Déconseillée `toNativeURL` fonction n'est pas prise en charge et n'est pas une ébauche. -fonction de `setMetadata` n'est pas stipulée dans le devis et pas pris en charge. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de SYNTAX_ERR(code: 8) sur la demande d'un système de fichier inexistant. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de PATH_EXISTS_ERR(code: 12) à essayer de créer exclusivement un fichier ou un répertoire, qui existe déjà. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NO_MODIFICATION_ALLOWED_ERR(code: 6) à essayer d'appeler removeRecursively sur le système de fichiers racine. -INVALID_MODIFICATION_ERR (code: 9) est levée au lieu de NOT_FOUND_ERR(code: 1) en essayant de moveTo répertoire qui n'existe pas.
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### Base IndexedDB impl bizarreries (Firefox et IE)
+
+* `.` et `.` ne sont pas pris en charge.
+* IE ne prend pas en charge les `file:///`-mode ; seul le mode hébergé est pris en charge (http://localhost:xxxx).
+* Taille de système de fichiers de Firefox n'est pas limité, mais chaque extension de 50Mo demandera une autorisation de l'utilisateur. IE10 permet jusqu'à 10 Mo de combiné AppCache et IndexedDB utilisés dans la mise en œuvre du système de fichiers sans demander de confirmation, une fois que vous atteignez ce niveau, Qu'on vous demandera si vous souhaitez lui permettre d'être augmentée jusqu'à un maximum de 250 Mo par site. Si le paramètre de `taille` pour la fonction `requestFileSystem` n'affecte pas le système de fichiers dans Firefox et IE.
+* fonction de `readAsBinaryString` n'est pas indiquée dans les spécifications et pas pris en charge dans Internet Explorer et n'a pas une ébauche.
+* `file.type` est toujours null.
+* Vous ne devez pas créer en utilisant le résultat du callback instance DirectoryEntry qui avait été supprimée. Sinon, vous obtiendrez une « entrée de pendaison ».
+* Avant que vous pouvez lire un fichier qui a été écrit juste que vous devez obtenir une nouvelle instance de ce fichier.
+* `setMetadata` fonction, qui n'est pas indiquée dans les spécifications supporte `modificationTime` changement de champ seulement.
+* fonctions `copyTo` et `moveTo` ne supportent pas les répertoires.
+* Répertoires métadonnées ne sont pas pris en charge.
+* Les deux Entry.remove et directoryEntry.removeRecursively ne manquent pas lors de la suppression des répertoires non-vides - répertoires retirés sont nettoyés avec contenu au lieu de cela.
+* fonctions `abort` et `truncate` ne sont pas supportées.
+* événements de progression ne sont pas déclenchés. Par exemple, ce gestionnaire ne sera pas exécuté :
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## Notes de mise à niveau
+
+V1.0.0 de ce plugin, les structures `FileEntry` et `DirectoryEntry` ont changé, pour être plus conforme à la spécification publiée.
+
+Les versions précédentes de (pré-1.0.0) du plugin stockaient le dispositif-absolu--emplacement du fichier dans la propriété `fullPath` d'objets `d'entrée`. Ces chemins seraient présente généralement comme
+
+ / var/mobile/Applications/< application UUID >/Documents/chemin/vers/fichier (iOS), /storage/emulated/0/path/to/file (Android)
+
+
+Ces chemins ont été également retournés par la méthode de `toURL()` les objets `d'entrée`.
+
+Avec v1.0.0, l'attribut `fullPath` est le chemin d'accès au fichier, *par rapport à la racine du système de fichiers HTML*. Ainsi, les chemins d'accès ci-dessus seraient maintenant tous les deux être représentée par un objet `FileEntry` avec un `fullPath` de
+
+ /path/to/file
+
+
+Si votre application fonctionne avec le dispositif-absolu-chemins et que vous avez récupéré précédemment ces chemins d'accès par le biais de la propriété `fullPath` d'objets `d'entrée`, puis vous devez mettre à jour votre code afin d'utiliser `entry.toURL()` à la place.
+
+Pour vers l'arrière la compatibilité, la méthode `resolveLocalFileSystemURL()` sera un chemin absolu de l'unité et retourne un objet `Entry` correspondant à elle, tant que ce fichier existe au sein des systèmes de fichiers les `TEMPORARY` ou `PERSISTENT`.
+
+Cela a été particulièrement un problème avec le plugin de transfert de fichiers, qui autrefois périphérique-absolu-chemins (et peut encore accepter). Il a été mis à jour pour fonctionner correctement avec le système de fichiers URL, afin de remplacer `entry.fullPath` par `entry.toURL()` devrait résoudre tout problème obtenir ce plugin pour travailler avec des fichiers sur le périphérique.
+
+Dans v1.1.0 la valeur de retour de `toURL()` a été changée (voir \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) pour renvoyer une URL absolue "file://". dans la mesure du possible. Pour assurer un ' cdvfile:'-URL, vous pouvez utiliser `toInternalURL()` maintenant. Cette méthode retourne maintenant filesystem URL du formulaire
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+qui peut servir à identifier de manière unique le fichier.
+
+## Liste des Codes d'erreur et leur signification
+
+Lorsqu'une erreur est levée, l'un des codes suivants sera utilisé.
+
+| Code | Constant |
+| ----:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configuration du Plugin (facultatif)
+
+L'ensemble des systèmes de fichiers disponibles peut être configurée par plate-forme. Les iOS et Android reconnaissent une balise dans le `fichier config.xml` qui nomme les systèmes de fichiers à installer. Par défaut, toutes les racines du système de fichiers sont activées.
+
+
+
+
+
+### Android
+
+* `files` : répertoire de stockage de fichier interne de l'application
+* `files-external` : répertoire de l'application de stockage de fichier externe
+* `sdcard` : le répertoire de stockage global fichier externe (c'est la racine de la carte SD, s'il est installé). Vous devez avoir la permission de `android.permission.WRITE_EXTERNAL_STORAGE` de l'utiliser.
+* `cache` : répertoire de cache interne de l'application
+* `cache-external` : répertoire de cache externe de l'application
+* `root` : le système de fichiers de tout dispositif
+
+Android prend également en charge un système de fichiers spécial nommé « documents », qui représente un sous-répertoire « / Documents / » dans le système de fichiers « files ».
+
+### iOS
+
+* `library` : répertoire de bibliothèque de l'application
+* `documents` : répertoire de Documents de l'application
+* `cache` : répertoire de Cache de l'application
+* `bundle` : bundle de l'application ; l'emplacement de l'application elle-même sur disque (lecture seule)
+* `root` : le système de fichiers de tout dispositif
+
+Par défaut, vous peuvent synchroniser les répertoires de la bibliothèque et les documents à iCloud. Vous pouvez également demander des deux systèmes de fichiers supplémentaires, `library-nosync` et `documents-nosync`, qui représentent un répertoire spécial non synchronisées dans le `/Library` ou système de fichiers `/ Documents`.
diff --git a/plugins/cordova-plugin-file/doc/fr/plugins.md b/plugins/cordova-plugin-file/doc/fr/plugins.md
new file mode 100644
index 0000000..b04e17f
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/fr/plugins.md
@@ -0,0 +1,101 @@
+
+
+# Notes pour les développeurs de plugins
+
+Ces notes sont principalement destinés à des développeurs Android et iOS qui veulent écrire des plugins qui interface avec le système de fichiers en utilisant le fichier plugin.
+
+## Travailler avec Cordova fichier système URL
+
+Depuis la version 1.0.0, ce plugin utilise des URL avec un `cdvfile` guichet pour toutes les communications sur le pont, plutôt que d'exposer des chemins de système de fichiers de périphérique brut à JavaScript.
+
+Du côté du JavaScript, cela signifie que les objets FileEntry et DirectoryEntry ont un attribut fullPath qui est relatif à la racine du système de fichiers HTML. Si votre plugin JavaScript API accepte un objet FileEntry ou DirectoryEntry, vous devez appeler `.toURL()` sur cet objet avant de le passer sur le pont en code natif.
+
+### Conversion de cdvfile: / / URL aux chemins d'accès fileystem
+
+Plugins qui ont besoin d'écrire dans le système de fichiers pouvez convertir un fichier reçu système URL vers un emplacement de système de fichiers réels. Il y a plusieurs façons de le faire, selon la plate-forme native.
+
+Il est important de rappeler que pas tous les `cdvfile://` URL sont cartographiables à des fichiers sur le périphérique. Certaines URL peut faire référence aux actifs sur les périphériques qui ne sont pas représentés par des fichiers, ou peuvent même faire référence aux ressources distantes. En raison de ces possibilités, plugins devraient toujours tester si ils obtiennent un résultat significatif retour lorsque vous essayez de convertir les URL aux chemins d'accès.
+
+#### Androïde
+
+Sur Android, la méthode la plus simple pour convertir un `cdvfile://` URL vers un chemin d'accès de système de fichiers est d'utiliser `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`possède plusieurs méthodes qui peuvent gérer `cdvfile://` URL :
+
+ webView est membre de la Plugin classe CordovaResourceApi resourceApi = webView.getResourceApi() ;
+
+ Obtenir une URL file:/// représentant ce fichier sur le périphérique, / / ou le même URL inchangée si elle ne peut pas être mappée à un fichier Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL)) ;
+
+
+Il est également possible d'utiliser le fichier plugin directement :
+
+ Import org.apache.cordova.file.FileUtils ;
+ Import org.apache.cordova.file.FileSystem ;
+ java.net.MalformedURLException d'importation ;
+
+ Téléchargez le fichier plugin depuis le gestionnaire de plugin FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File") ;
+
+ En donnant une URL, obtenir un chemin d'accès pour essayer {String path = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / l'url du système de fichiers n'a pas été reconnu}
+
+
+Pour convertir un chemin d'accès à un `cdvfile://` URL :
+
+ Import org.apache.cordova.file.LocalFilesystemURL ;
+
+ Obtenir un objet LocalFilesystemURL pour un chemin de périphérique, / / ou null si elle ne peut être représentée sous forme d'URL cdvfile.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path) ;
+ Obtenir la chaîne représentant l'URL objet String cdvfileURL = url.toString() ;
+
+
+Si votre plugin crée un fichier et que vous souhaitez renvoyer un objet FileEntry pour cela, utilisez le fichier plugin :
+
+ Retourne une structure JSON approprié pour revenir en JavaScript, / / ou null si ce fichier n'est pas représentable sous forme d'URL cdvfile.
+ JSONObject entrée = filePlugin.getEntryForFile(file) ;
+
+
+#### iOS
+
+Cordova sur iOS n'utilise pas le même `CordovaResourceApi` concept d'Android. Sur iOS, vous devez utiliser le fichier plugin pour convertir entre les URL et les chemins d'accès de système de fichiers.
+
+ Obtenir un objet URL CDVFilesystem partir d'une chaîne d'URL CDVFilesystemURL * url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL] ;
+ Obtenir un chemin d'accès de l'objet URL, ou zéro si elle ne peut pas être mappée à un chemin de fichier NSString * = [filePlugin filesystemPathForURL:url] ;
+
+
+ Obtenir un objet CDVFilesystem URL pour un chemin de périphérique, ou / / zéro si elle ne peut être représentée sous forme d'URL cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path] ;
+ Obtenir la représentation de chaîne de l'objet NSString * cdvfileURL URL = [url absoluteString] ;
+
+
+Si votre plugin crée un fichier et que vous souhaitez renvoyer un objet FileEntry pour cela, utilisez le fichier plugin :
+
+ Obtenir un objet CDVFilesystem URL pour un chemin de périphérique, ou / / zéro si elle ne peut être représentée sous forme d'URL cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path] ;
+ Obtenir une structure pour revenir à JavaScript NSDictionary * entrée = [filePlugin makeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+En JavaScript, pour obtenir un `cdvfile://` URL d'un objet FileEntry ou DirectoryEntry, il suffit d'appeler `.toURL()` à ce sujet :
+
+ var cdvfileURL = entry.toURL() ;
+
+
+Dans gestionnaires de plugin de réponse, pour convertir une structure FileEntry retournée vers un objet réel de l'entrée, votre code de gestionnaire doit importer le fichier plugin et créer un nouvel objet :
+
+ créer l'entrée de var d'objet entrée appropriée ;
+ Si (entryStruct.isDirectory) {entrée = new DirectoryEntry (entryStruct.name, entryStruct.fullPath, nouveau FileSystem(entryStruct.filesystemName));} else {entrée = nouvelle FileEntry (entryStruct.name, entryStruct.fullPath, nouvelle FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/it/README.md b/plugins/cordova-plugin-file/doc/it/README.md
new file mode 100644
index 0000000..f8e302f
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/it/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+Questo plugin implementa un API File permettendo l'accesso di lettura/scrittura ai file che risiedono sul dispositivo.
+
+Questo plugin si basa su diverse specifiche, tra cui: The HTML5 File API
+
+Le directory (ormai defunta) e il sistema delle estensioni più recenti: anche se la maggior parte del codice plugin è stato scritto quando una spec precedenti era corrente:
+
+Implementa inoltre FileWriter spec:
+
+Per l'utilizzo, fare riferimento a HTML5 Rocks' eccellente [articolo FileSystem.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+Per una panoramica delle altre opzioni di archiviazione, consultare [Guida di archiviazione di Cordova](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+Questo plugin definisce oggetto global `cordova.file`.
+
+Anche se in ambito globale, non è disponibile fino a dopo l'evento `deviceready`.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Installazione
+
+ cordova plugin add cordova-plugin-file
+
+
+## Piattaforme supportate
+
+ * Amazon fuoco OS
+ * Android
+ * BlackBerry 10
+ * Firefox OS
+ * iOS
+ * Windows Phone 7 e 8 *
+ * Windows 8 *
+ * Windows*
+ * Browser
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## Dove memorizzare i file
+
+A partire dalla v 1.2.0, vengono forniti gli URL per le directory importanti file di sistema. Ogni URL è nella forma *file:///path/to/spot/* e può essere convertito in un `DirectoryEntry` utilizzando `window.resolveLocalFileSystemURL()`.
+
+ * `cordova.file.applicationDirectory`-Sola lettura directory dove è installato l'applicazione. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.applicationStorageDirectory`-Directory radice di sandbox dell'applicazione; su iOS questa posizione è in sola lettura (ma sottodirectory specifiche [come `/Documents` ] sono di sola lettura). Tutti i dati contenuti all'interno è privato all'app. ( *iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.dataDirectory`-Archiviazione dati persistente e privati nella sandbox dell'applicazione utilizzando la memoria interna (su Android, se è necessario utilizzare la memoria esterna, utilizzare `.externalDataDirectory` ). IOS, questa directory non è sincronizzata con iCloud (utilizzare `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.cacheDirectory`-Directory per i file memorizzati nella cache di dati o qualsiasi file che app possibile ricreare facilmente. L'OS può eliminare questi file quando il dispositivo viene eseguito basso sull'archiviazione, tuttavia, apps non deve basarsi sul sistema operativo per cancellare i file qui. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-Spazio applicazione su storage esterno. (*Android*)
+
+ * `cordova.file.externalDataDirectory`-Dove mettere i file di dati specifico app su storage esterno. (*Android*)
+
+ * `cordova.file.externalCacheDirectory`-Cache applicazione su storage esterno. (*Android*)
+
+ * `cordova.file.externalRootDirectory`-Radice di archiviazione esterna (scheda SD). (*Android*, *BlackBerry, 10*)
+
+ * `cordova.file.tempDirectory`-Temp directory che l'OS è possibile cancellare a volontà. Non fare affidamento sul sistema operativo per cancellare questa directory; l'app deve sempre rimuovere file come applicabile. (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-Contiene i file app specifiche che devono essere sincronizzati (per esempio a iCloud). (*iOS*)
+
+ * `cordova.file.documentsDirectory`-I file privati per le app, ma che sono significativi per altre applicazioni (ad esempio i file di Office). (*iOS*)
+
+ * `cordova.file.sharedDirectory`-File disponibili globalmente a tutte le applicazioni (*BlackBerry 10*)
+
+## Layout dei file di sistema
+
+Anche se tecnicamente un dettaglio di implementazione, può essere molto utile per conoscere come le proprietà `cordova.file.*` mappa di percorsi fisici su un dispositivo reale.
+
+### iOS File sistema Layout
+
+| Percorso dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | r/w? | persistente? | OS cancella | sincronizzazione | privato |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:------------:|:------------:|:----------------:|:-------:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Sì |
+| `appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Sì |
+| `www/` | - | - | r | N/A | N/A | N/A | Sì |
+| `Documents/` | documentsDirectory | documenti | r/w | Sì | No | Sì | Sì |
+| `NoCloud/` | - | nosync-documenti | r/w | Sì | No | No | Sì |
+| `Library` | - | libreria | r/w | Sì | No | Sì? | Sì |
+| `NoCloud/` | dataDirectory | nosync-libreria | r/w | Sì | No | No | Sì |
+| `Cloud/` | syncedDataDirectory | - | r/w | Sì | No | Sì | Sì |
+| `Caches/` | cacheDirectory | cache | r/w | Sì * | Sì**\* | No | Sì |
+| `tmp/` | tempDirectory | - | r/w | No** | Sì**\* | No | Sì |
+
+\ * File persistono tra riavvii app e aggiornamenti, ma questa directory può essere cancellata ogni volta che il sistema operativo desideri. L'app dovrebbe essere in grado di ricreare qualsiasi contenuto che potrebbe essere eliminato.
+
+** File possono persistere riavvii del app, ma non fare affidamento su questo comportamento. I file non sono garantiti a persistere attraverso gli aggiornamenti. L'app deve rimuovere i file dalla directory quando è applicabile, come il sistema operativo non garantisce quando (o anche se) questi file vengono rimossi.
+
+**\ * The OS può cancellare il contenuto di questa directory ogni volta che si sente è necessario, ma non fare affidamento su questo. Si dovrebbe cancellare questa directory come adatto per l'applicazione.
+
+### Layout sistema Android File
+
+| Percorso dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistente? | OS cancella | privato |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:------------:|:-----------:|:-------:|
+| `File:///android_asset/` | applicationDirectory | | r | N/A | N/A | Sì |
+| `< app-id > /dati/dati / /` | applicationStorageDirectory | - | r/w | N/A | N/A | Sì |
+| `cache` | cacheDirectory | cache | r/w | Sì | Sì\* | Sì |
+| `files` | dataDirectory | file | r/w | Sì | No | Sì |
+| `Documents` | | documenti | r/w | Sì | No | Sì |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sì | No | No |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sì | No | No |
+| `cache` | externalCacheDirectry | cache-esterno | r/w | Sì | No** | No |
+| `files` | externalDataDirectory | file-esterno | r/w | Sì | No | No |
+
+\ * Il sistema operativo può cancellare periodicamente questa directory, ma non fare affidamento su questo comportamento. Cancellare il contenuto di questa directory come adatto per l'applicazione. Il contenuto di questa directory dovrebbe un utente eliminare manualmente la cache, vengono rimossi.
+
+** Il sistema operativo non cancella questa directory automaticamente; Siete responsabili di gestire i contenuti da soli. Il contenuto della directory dovrebbe l'utente eliminare manualmente la cache, vengono rimossi.
+
+**Nota**: se la memorizzazione esterna non può essere montato, le proprietà `cordova.file.external*` sono `null`.
+
+### BlackBerry 10 File sistema Layout
+
+| Percorso dispositivo | `Cordova.file.*` | r/w? | persistente? | OS cancella | privato |
+|:----------------------------------------------------------- |:--------------------------- |:----:|:------------:|:-----------:|:-------:|
+| `File:///accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Sì |
+| `app/native` | applicationDirectory | r | N/A | N/A | Sì |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sì | Sì |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sì | No | Sì |
+| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sì | No | No |
+| `File:///accounts/1000/Shared` | sharedDirectory | r/w | Sì | No | No |
+
+*Nota*: quando l'applicazione viene distribuita a lavorare perimetrale, tutti i percorsi sono relativi a /accounts/1000-enterprise.
+
+## Stranezze Android
+
+### Posizione di archiviazione persistente Android
+
+Ci sono più percorsi validi per memorizzare i file persistenti su un dispositivo Android. Vedi [questa pagina](http://developer.android.com/guide/topics/data/data-storage.html) per un'ampia discussione delle varie possibilità.
+
+Versioni precedenti del plugin avrebbe scelto il percorso dei file temporanei e permanenti su avvio, in base se il dispositivo ha sostenuto che la scheda SD (o partizione storage equivalente) è stato montato. Se è stata montata sulla scheda SD o una partizione di storage interno grande era disponibile (come sui dispositivi Nexus,) allora saranno memorizzati i file persistenti nella radice di quello spazio. Questo significava che tutte le apps di Cordova poteva vedere tutti i file disponibili sulla carta.
+
+Se la scheda SD non era disponibile, poi versioni precedenti vuoi memorizzare dati sotto `/data/data/`, che isola i apps da altro, ma può ancora causa dati da condividere tra gli utenti.
+
+Ora è possibile scegliere se memorizzare i file nel percorso di archiviazione di file interno o utilizzando la logica precedente, con una preferenza nel file `config. xml` dell'applicazione. Per fare questo, aggiungere una di queste due linee al `file config. xml`:
+
+
+
+
+
+
+Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia.
+
+Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione su "Interno" di commutazione significherebbe che gli utenti esistenti che aggiornare la loro applicazione potrebbero essere Impossibile accedere ai loro file precedentemente memorizzati, a seconda del loro dispositivo.
+
+Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione `Internal`.
+
+### Operazioni ricorsive lento per /android_asset
+
+L'elencazione delle directory asset è veramente lento su Android. È possibile velocizzare e fino anche se, con l'aggiunta di `src/android/build-extras.gradle` alla radice del tuo progetto android (richiede anche cordova-android@4.0.0 o superiore).
+
+## iOS stranezze
+
+ * `cordova.file.applicationStorageDirectory`è di sola lettura; tentativo di memorizzare i file all'interno della directory radice avrà esito negativo. Utilizzare uno degli altri `cordova.file.*` proprietà definite per iOS (solo `applicationDirectory` e `applicationStorageDirectory` sono di sola lettura).
+ * `FileReader.readAsText(blob, encoding)`
+ * Il `encoding` parametro non è supportato, e codifica UTF-8 è sempre attivo.
+
+### posizione di archiviazione persistente di iOS
+
+Ci sono due percorsi validi per memorizzare i file persistenti su un dispositivo iOS: la directory documenti e la biblioteca. Precedenti versioni del plugin archiviati solo mai persistenti file nella directory documenti. Questo ha avuto l'effetto collaterale di tutti i file di un'applicazione che rende visibili in iTunes, che era spesso involontaria, soprattutto per le applicazioni che gestiscono un sacco di piccoli file, piuttosto che produrre documenti completi per l'esportazione, che è la destinazione della directory.
+
+Ora è possibile scegliere se memorizzare i file nella directory di libreria, con una preferenza nel file `config. xml` dell'applicazione o documenti. Per fare questo, aggiungere una di queste due linee al `file config. xml`:
+
+
+
+
+
+
+Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia.
+
+Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione di commutazione alla `libreria` significherebbe che gli utenti esistenti che aggiornare la loro applicazione è in grado di accedere ai loro file precedentemente memorizzati.
+
+Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione della `Library`.
+
+## Firefox OS stranezze
+
+L'API di sistema del File non è supportato nativamente dal sistema operativo Firefox e viene implementato come uno spessore in cima indexedDB.
+
+ * Non manca quando si rimuove le directory non vuota
+ * Non supporta i metadati per le directory
+ * Metodi `copyTo` e `moveTo` non supporta le directory
+
+Sono supportati i seguenti percorsi di dati: * `applicationDirectory` - utilizza `xhr` per ottenere i file locali che sono confezionati con l'app. *`dataDirectory` - per i file di dati persistenti app specifiche. *`cacheDirectory` - file memorizzati nella cache che dovrebbe sopravvivere si riavvia app (applicazioni non devono basarsi sull'OS di eliminare i file qui).
+
+## Stranezze browser
+
+### Stranezze e osservazioni comuni
+
+ * Ogni browser utilizza il proprio filesystem in modalità sandbox. IE e Firefox utilizzare IndexedDB come base. Tutti i browser utilizzano barra come separatore di directory in un percorso.
+ * Le voci di directory devono essere creato successivamente. Ad esempio, la chiamata `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` non riuscirà se non esistesse dir1.
+ * Il plugin richiede autorizzazione utente per utilizzare un archivio permanente presso il primo avvio dell'applicazione.
+ * Plugin supporta `cdvfile://localhost` (risorse locali) solo. Cioè risorse esterne non sono supportate tramite `cdvfile`.
+ * Il plugin non segue ["Limitazioni di denominazione 8.3 File sistema API"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
+ * BLOB e File' `close` la funzione non è supportata.
+ * `FileSaver` e `BlobBuilder` non sono supportati da questo plugin e non hanno gli stub.
+ * Il plugin non supporta `requestAllFileSystems`. Questa funzione manca anche nelle specifiche.
+ * Entrate nella directory non verranno rimossi se si utilizza `create: true` bandiera per directory esistente.
+ * Non sono supportati i file creati tramite il costruttore. È invece necessario utilizzare il metodo entry.file.
+ * Ogni browser utilizza la propria forma per riferimenti URL blob.
+ * `readAsDataURL` funzione è supportata, ma il mediatype in Chrome dipende dall'estensione di voce, mediatype in IE è sempre vuota (che è lo stesso come `text-plain` secondo la specifica), il mediatype in Firefox è sempre `application/octet-stream`. Ad esempio, se il contenuto è `abcdefg` quindi Firefox restituisce `dati: applicazione / octet-stream; base64, YWJjZGVmZw = =`, cioè restituisce `dati:; base64, YWJjZGVmZw = =`, Chrome restituisce `dati: < mediatype a seconda dell'estensione del nome della voce >; base64, YWJjZGVmZw = =`.
+ * `toInternalURL` restituisce il percorso in forma `file:///persistent/path/to/entry` (Firefox, IE). Chrome restituisce il percorso nella forma `cdvfile://localhost/persistent/file`.
+
+### Stranezze di cromo
+
+ * Cromo filesystem non è subito pronto dopo evento ready dispositivo. Come soluzione alternativa, è possibile iscriversi all'evento `filePluginIsReady`. Esempio:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+È possibile utilizzare la funzione `window.isFilePluginReadyRaised` per verificare se evento già è stato generato. -quote di filesystem TEMPORARY e PERSISTENT window.requestFileSystem non sono limitate in Chrome. -Per aumentare la memoria persistente in Chrome è necessario chiamare il metodo `window.initPersistentFileSystem`. Quota di archiviazione persistente è di 5 MB per impostazione predefinita. -Chrome richiede `-consentire-file-accesso-da-file` eseguire argomento a supporto API tramite protocollo `file:///`. -`File` oggetto non cambierà se si utilizza il flag `{create:true}` quando ottenendo un' esistente `entrata`. -eventi `cancelable` è impostata su true in Chrome. Ciò è in contrasto con la [specifica](http://dev.w3.org/2009/dap/file-system/file-writer.html). -funzione `toURL` Chrome restituisce `filesystem:`-premessi percorso a seconda dell'applicazione host. Ad esempio, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` risultato di funzione non contiene una barra finale in caso di voce di directory. Chrome risolve le directory con gli URL slash-trainati però correttamente. -`resolveLocalFileSystemURL` metodo richiede in ingresso `url` avere il prefisso del `file System`. Ad esempio, il parametro `url` per `resolveLocalFileSystemURL` dovrebbe essere nella forma `filesystem:file:///persistent/somefile.txt` in contrasto con la forma `file:///persistent/somefile.txt` in Android. -Obsoleto `toNativeURL` funzione non è supportata e non dispone di uno stub. -funzione `setMetadata` non è indicato nelle specifiche e non supportato. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di SYNTAX_ERR(code: 8) su richiesta di un filesystem inesistente. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di PATH_EXISTS_ERR(code: 12) sul tentativo di creare esclusivamente un file o una directory, che esiste già. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NO_MODIFICATION_ALLOWED_ERR(code: 6) sul tentativo di chiamare removeRecursively su file system root. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NOT_FOUND_ERR(code: 1) sul tentativo moveTo directory che non esiste.
+
+### Stranezze impl IndexedDB-basato (Firefox e IE)
+
+ * `.` e `.` non sono supportati.
+ * IE non supporta `file:///`-modalità; modalità solo ospitata è supportato (http://localhost:xxxx).
+ * Dimensione filesystem Firefox non è limitata, ma ogni estensione 50MB sarà richiesta un'autorizzazione dell'utente. IE10 consente fino a 10mb di combinato AppCache e IndexedDB utilizzato nell'implementazione del filesystem senza chiedere conferma, una volta premuto quel livello che vi verrà chiesto se si desidera consentire ad essere aumentata fino a un max di 250 mb per ogni sito. Quindi la `size` parametro per la funzione `requestFileSystem` non influisce il filesystem in Firefox e IE.
+ * `readAsBinaryString` funzione non è indicato nelle specifiche e non supportati in IE e non dispone di uno stub.
+ * `file.Type` è sempre null.
+ * Non è necessario creare la voce utilizzando il risultato del callback istanza DirectoryEntry che è stato eliminato. In caso contrario, si otterrà una 'voce di sospensione'.
+ * Prima è possibile leggere un file che è stato appena scritto è necessario ottenere una nuova istanza di questo file.
+ * supporta la funzione `setMetadata`, che non è indicato nelle specifiche `modificationTime` cambiamento di campo solo.
+ * funzioni `copyTo` e `moveTo` non supporta le directory.
+ * Le directory metadati non sono supportato.
+ * Sia Entry.remove e directoryEntry.removeRecursively non fallire quando si rimuove le directory non vuota - directory da rimuovere vengono pulite invece insieme al contenuto.
+ * `abort` e `truncate` le funzioni non sono supportate.
+ * non vengono generati eventi di progresso. Ad esempio, questo gestore verrà non eseguito:
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## Note di aggiornamento
+
+In v 1.0.0 di questo plugin, le strutture `FileEntry` e `DirectoryEntry` sono cambiati, per essere più in linea con le specifiche pubblicate.
+
+Versioni precedenti (pre-1.0.0) del plugin archiviati il dispositivo-assoluto--percorso del file nella proprietà `fullPath` di oggetti della `voce`. In genere questi percorsi si sarebbe simile
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Questi percorsi sono stati anche restituiti dal metodo `toURL()` degli oggetti `Entry`.
+
+Con v 1.0.0, l'attributo `fullPath` è il percorso del file, *rispetto alla radice del filesystem HTML*. Così, i percorsi sopra sarebbe ora sia rappresentato da un oggetto `FileEntry` con un `fullPath` di
+
+ /path/to/file
+
+
+Se l'applicazione funziona con dispositivo-assoluto-percorsi, e precedentemente recuperato quei percorsi attraverso la proprietà `fullPath` della `voce` oggetti, è necessario aggiornare il codice per utilizzare `entry.toURL()` invece.
+
+Per indietro la compatibilità, il metodo `resolveLocalFileSystemURL()` verrà accettare un dispositivo-assoluto-percorso e restituirà un oggetto di `entrata` corrispondente ad essa, fintanto che il file esiste all'interno del filesystem la `temporanea` o `permanente`.
+
+Questo particolare è stato un problema con il plugin di trasferimento File, che in precedenza utilizzati percorsi-dispositivo-assoluto (e ancora può accoglierli). Esso è stato aggiornato per funzionare correttamente con gli URL di FileSystem, così sostituendo `entry.fullPath` con `entry.toURL()` dovrebbe risolvere eventuali problemi ottenendo quel plugin per lavorare con i file nel dispositivo.
+
+In v 1.1.0 il valore restituito di `toURL()` è stato cambiato (vedere \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) per restituire un URL assoluto 'file://'. ove possibile. Per assicurare un ' cdvfile:'-URL, è possibile utilizzare `toInternalURL()` ora. Questo metodo restituirà ora filesystem URL del modulo
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+che può essere utilizzato per identificare univocamente il file.
+
+## Elenco dei codici di errore e significati
+
+Quando viene generato un errore, uno dei seguenti codici da utilizzare.
+
+| Codice | Costante |
+| ------:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configurare il Plugin (opzionale)
+
+Il set di filesystem disponibili può essere configurato per ogni piattaforma. Sia iOS che Android riconoscere un Tag nel `file config. xml` che nomina il filesystem per essere installato. Per impostazione predefinita, tutte le radici del file system sono abilitate.
+
+
+
+
+
+### Android
+
+ * `files`: directory di archiviazione di file interno dell'applicazione
+ * `files-external`: directory di archiviazione dell'applicazione file esterno
+ * `sdcard`: la directory di archiviazione di file esterni globale (questa è la radice della scheda SD, se uno è installato). È necessario disporre dell'autorizzazione `android.permission.WRITE_EXTERNAL_STORAGE` utilizzare questo.
+ * `cache`: la cache interna directory applicazione
+ * `cache-external`: directory di cache esterna dell'applicazione
+ * `root`: il dispositivo intero filesystem
+
+Android supporta anche un filesystem speciale denominato "documenti", che rappresenta una sottodirectory "/ documenti /" all'interno del filesystem "files".
+
+### iOS
+
+ * `library`: la directory dell'applicazione libreria
+ * `documents`: la directory dell'applicazione documenti
+ * `cache`: la Cache directory applicazione
+ * `bundle`: bundle dell'applicazione; la posizione dell'app sul disco (sola lettura)
+ * `root`: il dispositivo intero filesystem
+
+Per impostazione predefinita, la directory di libreria e documenti può essere sincronizzata a iCloud. È anche possibile richiedere due filesystem aggiuntivi, `library-nosync` e `documents-nosync`, che rappresentano una speciale directory non sincronizzati entro il `/Library` o filesystem `/Documents`.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/it/index.md b/plugins/cordova-plugin-file/doc/it/index.md
new file mode 100644
index 0000000..f3cd731
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/it/index.md
@@ -0,0 +1,338 @@
+
+
+# cordova-plugin-file
+
+Questo plugin implementa un API File permettendo l'accesso di lettura/scrittura ai file che risiedono sul dispositivo.
+
+Questo plugin si basa su diverse specifiche, tra cui: The HTML5 File API
+
+Le directory (ormai defunta) e il sistema delle estensioni più recenti: anche se la maggior parte del codice plugin è stato scritto quando una spec precedenti era corrente:
+
+Implementa inoltre FileWriter spec:
+
+Per l'utilizzo, fare riferimento a HTML5 Rocks' eccellente [articolo FileSystem.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+Per una panoramica delle altre opzioni di archiviazione, consultare [Guida di archiviazione di Cordova][2].
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+Questo plugin definisce oggetto global `cordova.file`.
+
+Anche se in ambito globale, non è disponibile fino a dopo l'evento `deviceready`.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Installazione
+
+ cordova plugin add cordova-plugin-file
+
+
+## Piattaforme supportate
+
+* Amazon fuoco OS
+* Android
+* BlackBerry 10
+* Firefox OS
+* iOS
+* Windows Phone 7 e 8 *
+* Windows 8 *
+* Browser
+
+* *Queste piattaforme non supportano `FileReader.readAsArrayBuffer` né `FileWriter.write(blob)`.*
+
+## Dove memorizzare i file
+
+A partire dalla v 1.2.0, vengono forniti gli URL per le directory importanti file di sistema. Ogni URL è nella forma *file:///path/to/spot/* e può essere convertito in un `DirectoryEntry` utilizzando `window.resolveLocalFileSystemURL()`.
+
+* `cordova.file.applicationDirectory`-Sola lettura directory dove è installato l'applicazione. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.applicationStorageDirectory`-Directory radice di sandbox dell'applicazione; su iOS questa posizione è in sola lettura (ma sottodirectory specifiche [come `/Documents` ] sono di sola lettura). Tutti i dati contenuti all'interno è privato all'app. ( *iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.dataDirectory`-Archiviazione dati persistente e privati nella sandbox dell'applicazione utilizzando la memoria interna (su Android, se è necessario utilizzare la memoria esterna, utilizzare `.externalDataDirectory` ). IOS, questa directory non è sincronizzata con iCloud (utilizzare `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.cacheDirectory`-Directory per i file memorizzati nella cache di dati o qualsiasi file che app possibile ricreare facilmente. L'OS può eliminare questi file quando il dispositivo viene eseguito basso sull'archiviazione, tuttavia, apps non deve basarsi sul sistema operativo per cancellare i file qui. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-Spazio applicazione su storage esterno. (*Android*)
+
+* `cordova.file.externalDataDirectory`-Dove mettere i file di dati specifico app su storage esterno. (*Android*)
+
+* `cordova.file.externalCacheDirectory`-Cache applicazione su storage esterno. (*Android*)
+
+* `cordova.file.externalRootDirectory`-Radice di archiviazione esterna (scheda SD). (*Android*, *BlackBerry, 10*)
+
+* `cordova.file.tempDirectory`-Temp directory che l'OS è possibile cancellare a volontà. Non fare affidamento sul sistema operativo per cancellare questa directory; l'app deve sempre rimuovere file come applicabile. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-Contiene i file app specifiche che devono essere sincronizzati (per esempio a iCloud). (*iOS*)
+
+* `cordova.file.documentsDirectory`-I file privati per le app, ma che sono significativi per altre applicazioni (ad esempio i file di Office). (*iOS*)
+
+* `cordova.file.sharedDirectory`-File disponibili globalmente a tutte le applicazioni (*BlackBerry 10*)
+
+## Layout dei file di sistema
+
+Anche se tecnicamente un dettaglio di implementazione, può essere molto utile per conoscere come le proprietà `cordova.file.*` mappa di percorsi fisici su un dispositivo reale.
+
+### iOS File sistema Layout
+
+| Percorso dispositivo | `Cordova.file.*` | `iosExtraFileSystems` | r/w? | persistente? | OS cancella | sincronizzazione | privato |
+|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:------------:|:-----------:|:----------------:|:-------:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Sì |
+| `appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Sì |
+| `www/` | - | - | r | N/A | N/A | N/A | Sì |
+| `Documents/` | documentsDirectory | documenti | r/w | Sì | No | Sì | Sì |
+| `NoCloud/` | - | nosync-documenti | r/w | Sì | No | No | Sì |
+| `Library` | - | libreria | r/w | Sì | No | Sì? | Sì |
+| `NoCloud/` | dataDirectory | nosync-libreria | r/w | Sì | No | No | Sì |
+| `Cloud/` | syncedDataDirectory | - | r/w | Sì | No | Sì | Sì |
+| `Caches/` | cacheDirectory | cache | r/w | Sì * | Sì * * *| | No | Sì |
+| `tmp/` | tempDirectory | - | r/w | No * * | Sì * * *| | No | Sì |
+
+* File persistono attraverso riavvii app e aggiornamenti, ma questa directory può essere azzerata ogni volta che desideri l'OS. L'app dovrebbe essere in grado di ricreare qualsiasi contenuto che potrebbe essere eliminato.
+
+* * File può persistere attraverso app riavvii, ma non fare affidamento su questo comportamento. I file non sono garantiti a persistere attraverso gli aggiornamenti. L'app deve rimuovere i file dalla directory quando è applicabile, come il sistema operativo non garantisce quando (o anche se) questi file vengono rimossi.
+
+* * *| Il sistema operativo può cancellare il contenuto di questa directory ogni volta che si sente è necessario, ma non fare affidamento su questo. Si dovrebbe cancellare questa directory come adatto per l'applicazione.
+
+### Layout sistema Android File
+
+| Percorso dispositivo | `Cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistente? | OS cancella | privato |
+|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:------------:|:-----------:|:-------:|
+| `File:///android_asset/` | applicationDirectory | | r | N/A | N/A | Sì |
+| `< app-id > /dati/dati / /` | applicationStorageDirectory | - | r/w | N/A | N/A | Sì |
+| `cache` | cacheDirectory | cache | r/w | Sì | Sì * | Sì |
+| `files` | dataDirectory | file | r/w | Sì | No | Sì |
+| `Documents` | | documenti | r/w | Sì | No | Sì |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Sì | No | No |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Sì | No | No |
+| `cache` | externalCacheDirectry | cache-esterno | r/w | Sì | No * * | No |
+| `files` | externalDataDirectory | file-esterno | r/w | Sì | No | No |
+
+* Il sistema operativo può cancellare periodicamente questa directory, ma non fare affidamento su questo comportamento. Cancellare il contenuto di questa directory come adatto per l'applicazione. Il contenuto di questa directory dovrebbe un utente eliminare manualmente la cache, vengono rimossi.
+
+* * Il sistema operativo non cancella questa directory automaticamente; Tu sei responsabile per la gestione dei contenuti da soli. Il contenuto della directory dovrebbe l'utente eliminare manualmente la cache, vengono rimossi.
+
+**Nota**: se la memorizzazione esterna non può essere montato, le proprietà `cordova.file.external*` sono `null`.
+
+### BlackBerry 10 File sistema Layout
+
+| Percorso dispositivo | `Cordova.file.*` | r/w? | persistente? | OS cancella | privato |
+|:--------------------------------------------------- |:--------------------------- |:----:|:------------:|:-----------:|:-------:|
+| `File:///accounts/1000/AppData/ < id app > /` | applicationStorageDirectory | r | N/A | N/A | Sì |
+| `app/native` | applicationDirectory | r | N/A | N/A | Sì |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Sì | Sì |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Sì | No | Sì |
+| `File:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Sì | No | No |
+| `File:///accounts/1000/Shared` | sharedDirectory | r/w | Sì | No | No |
+
+*Nota*: quando l'applicazione viene distribuita a lavorare perimetrale, tutti i percorsi sono relativi a /accounts/1000-enterprise.
+
+## Stranezze Android
+
+### Posizione di archiviazione persistente Android
+
+Ci sono più percorsi validi per memorizzare i file persistenti su un dispositivo Android. Vedi [questa pagina][3] per un'ampia discussione delle varie possibilità.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+Versioni precedenti del plugin avrebbe scelto il percorso dei file temporanei e permanenti su avvio, in base se il dispositivo ha sostenuto che la scheda SD (o partizione storage equivalente) è stato montato. Se è stata montata sulla scheda SD o una partizione di storage interno grande era disponibile (come sui dispositivi Nexus,) allora saranno memorizzati i file persistenti nella radice di quello spazio. Questo significava che tutte le apps di Cordova poteva vedere tutti i file disponibili sulla carta.
+
+Se la scheda SD non era disponibile, poi versioni precedenti vuoi memorizzare dati sotto `/data/data/`, che isola i apps da altro, ma può ancora causa dati da condividere tra gli utenti.
+
+Ora è possibile scegliere se memorizzare i file nel percorso di archiviazione di file interno o utilizzando la logica precedente, con una preferenza nel file `config. xml` dell'applicazione. Per fare questo, aggiungere una di queste due linee al `file config. xml`:
+
+
+
+
+
+
+Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia.
+
+Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione su "Interno" di commutazione significherebbe che gli utenti esistenti che aggiornare la loro applicazione potrebbero essere Impossibile accedere ai loro file precedentemente memorizzati, a seconda del loro dispositivo.
+
+Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione `Internal`.
+
+## iOS stranezze
+
+* `cordova.file.applicationStorageDirectory`è di sola lettura; tentativo di memorizzare i file all'interno della directory radice avrà esito negativo. Utilizzare uno degli altri `cordova.file.*` proprietà definite per iOS (solo `applicationDirectory` e `applicationStorageDirectory` sono di sola lettura).
+* `FileReader.readAsText(blob, encoding)`
+ * Il `encoding` parametro non è supportato, e codifica UTF-8 è sempre attivo.
+
+### posizione di archiviazione persistente di iOS
+
+Ci sono due percorsi validi per memorizzare i file persistenti su un dispositivo iOS: la directory documenti e la biblioteca. Precedenti versioni del plugin archiviati solo mai persistenti file nella directory documenti. Questo ha avuto l'effetto collaterale di tutti i file di un'applicazione che rende visibili in iTunes, che era spesso involontaria, soprattutto per le applicazioni che gestiscono un sacco di piccoli file, piuttosto che produrre documenti completi per l'esportazione, che è la destinazione della directory.
+
+Ora è possibile scegliere se memorizzare i file nella directory di libreria, con una preferenza nel file `config. xml` dell'applicazione o documenti. Per fare questo, aggiungere una di queste due linee al `file config. xml`:
+
+
+
+
+
+
+Senza questa linea, il File del plugin utilizzerà la `Compatibility` come predefinito. Se è presente un tag di preferenza e non è uno di questi valori, l'applicazione non si avvia.
+
+Se l'applicazione è stato spedito in precedenza agli utenti, utilizzando un vecchio (pre-1.0) versione di questo plugin e ha i file memorizzati nel filesystem persistente, allora si dovrebbe impostare la preferenza di `Compatibility`. La posizione di commutazione alla `libreria` significherebbe che gli utenti esistenti che aggiornare la loro applicazione è in grado di accedere ai loro file precedentemente memorizzati.
+
+Se l'applicazione è nuova, o ha mai precedentemente memorizzati i file nel filesystem persistente, è generalmente consigliato l'impostazione della `Library`.
+
+## Firefox OS stranezze
+
+L'API di sistema del File non è supportato nativamente dal sistema operativo Firefox e viene implementato come uno spessore in cima indexedDB.
+
+* Non manca quando si rimuove le directory non vuota
+* Non supporta i metadati per le directory
+* Metodi `copyTo` e `moveTo` non supporta le directory
+
+Sono supportati i seguenti percorsi di dati: * `applicationDirectory` - utilizza `xhr` per ottenere i file locali che sono confezionati con l'app. *`dataDirectory` - per i file di dati persistenti app specifiche. *`cacheDirectory` - file memorizzati nella cache che dovrebbe sopravvivere si riavvia app (applicazioni non devono basarsi sull'OS di eliminare i file qui).
+
+## Stranezze browser
+
+### Stranezze e osservazioni comuni
+
+* Ogni browser utilizza il proprio filesystem in modalità sandbox. IE e Firefox utilizzare IndexedDB come base. Tutti i browser utilizzano barra come separatore di directory in un percorso.
+* Le voci di directory devono essere creato successivamente. Ad esempio, la chiamata `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` non riuscirà se non esistesse dir1.
+* Il plugin richiede autorizzazione utente per utilizzare un archivio permanente presso il primo avvio dell'applicazione.
+* Plugin supporta `cdvfile://localhost` (risorse locali) solo. Cioè risorse esterne non sono supportate tramite `cdvfile`.
+* Il plugin non segue ["Limitazioni di denominazione 8.3 File sistema API"][4].
+* BLOB e File' `close` la funzione non è supportata.
+* `FileSaver` e `BlobBuilder` non sono supportati da questo plugin e non hanno gli stub.
+* Il plugin non supporta `requestAllFileSystems`. Questa funzione manca anche nelle specifiche.
+* Entrate nella directory non verranno rimossi se si utilizza `create: true` bandiera per directory esistente.
+* Non sono supportati i file creati tramite il costruttore. È invece necessario utilizzare il metodo entry.file.
+* Ogni browser utilizza la propria forma per riferimenti URL blob.
+* `readAsDataURL` funzione è supportata, ma il mediatype in Chrome dipende dall'estensione di voce, mediatype in IE è sempre vuota (che è lo stesso come `text-plain` secondo la specifica), il mediatype in Firefox è sempre `application/octet-stream`. Ad esempio, se il contenuto è `abcdefg` quindi Firefox restituisce `dati: applicazione / octet-stream; base64, YWJjZGVmZw = =`, cioè restituisce `dati:; base64, YWJjZGVmZw = =`, Chrome restituisce `dati: < mediatype a seconda dell'estensione del nome della voce >; base64, YWJjZGVmZw = =`.
+* `toInternalURL` restituisce il percorso in forma `file:///persistent/path/to/entry` (Firefox, IE). Chrome restituisce il percorso nella forma `cdvfile://localhost/persistent/file`.
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### Stranezze di cromo
+
+* Cromo filesystem non è subito pronto dopo evento ready dispositivo. Come soluzione alternativa, è possibile iscriversi all'evento `filePluginIsReady`. Esempio:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+È possibile utilizzare la funzione `window.isFilePluginReadyRaised` per verificare se evento già è stato generato. -quote di filesystem TEMPORARY e PERSISTENT window.requestFileSystem non sono limitate in Chrome. -Per aumentare la memoria persistente in Chrome è necessario chiamare il metodo `window.initPersistentFileSystem`. Quota di archiviazione persistente è di 5 MB per impostazione predefinita. -Chrome richiede `-consentire-file-accesso-da-file` eseguire argomento a supporto API tramite protocollo `file:///`. -`File` oggetto non cambierà se si utilizza il flag `{create:true}` quando ottenendo un' esistente `entrata`. -eventi `cancelable` è impostata su true in Chrome. Ciò è in contrasto con la [specifica][5]. -funzione `toURL` Chrome restituisce `filesystem:`-premessi percorso a seconda dell'applicazione host. Ad esempio, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` risultato di funzione non contiene una barra finale in caso di voce di directory. Chrome risolve le directory con gli URL slash-trainati però correttamente. -`resolveLocalFileSystemURL` metodo richiede in ingresso `url` avere il prefisso del `file System`. Ad esempio, il parametro `url` per `resolveLocalFileSystemURL` dovrebbe essere nella forma `filesystem:file:///persistent/somefile.txt` in contrasto con la forma `file:///persistent/somefile.txt` in Android. -Obsoleto `toNativeURL` funzione non è supportata e non dispone di uno stub. -funzione `setMetadata` non è indicato nelle specifiche e non supportato. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di SYNTAX_ERR(code: 8) su richiesta di un filesystem inesistente. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di PATH_EXISTS_ERR(code: 12) sul tentativo di creare esclusivamente un file o una directory, che esiste già. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NO_MODIFICATION_ALLOWED_ERR(code: 6) sul tentativo di chiamare removeRecursively su file system root. -INVALID_MODIFICATION_ERR (codice: 9) viene generata invece di NOT_FOUND_ERR(code: 1) sul tentativo moveTo directory che non esiste.
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### Stranezze impl IndexedDB-basato (Firefox e IE)
+
+* `.` e `.` non sono supportati.
+* IE non supporta `file:///`-modalità; modalità solo ospitata è supportato (http://localhost:xxxx).
+* Dimensione filesystem Firefox non è limitata, ma ogni estensione 50MB sarà richiesta un'autorizzazione dell'utente. IE10 consente fino a 10mb di combinato AppCache e IndexedDB utilizzato nell'implementazione del filesystem senza chiedere conferma, una volta premuto quel livello che vi verrà chiesto se si desidera consentire ad essere aumentata fino a un max di 250 mb per ogni sito. Quindi la `size` parametro per la funzione `requestFileSystem` non influisce il filesystem in Firefox e IE.
+* `readAsBinaryString` funzione non è indicato nelle specifiche e non supportati in IE e non dispone di uno stub.
+* `file.Type` è sempre null.
+* Non è necessario creare la voce utilizzando il risultato del callback istanza DirectoryEntry che è stato eliminato. In caso contrario, si otterrà una 'voce di sospensione'.
+* Prima è possibile leggere un file che è stato appena scritto è necessario ottenere una nuova istanza di questo file.
+* supporta la funzione `setMetadata`, che non è indicato nelle specifiche `modificationTime` cambiamento di campo solo.
+* funzioni `copyTo` e `moveTo` non supporta le directory.
+* Le directory metadati non sono supportato.
+* Sia Entry.remove e directoryEntry.removeRecursively non fallire quando si rimuove le directory non vuota - directory da rimuovere vengono pulite invece insieme al contenuto.
+* `abort` e `truncate` le funzioni non sono supportate.
+* non vengono generati eventi di progresso. Ad esempio, questo gestore verrà non eseguito:
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## Note di aggiornamento
+
+In v 1.0.0 di questo plugin, le strutture `FileEntry` e `DirectoryEntry` sono cambiati, per essere più in linea con le specifiche pubblicate.
+
+Versioni precedenti (pre-1.0.0) del plugin archiviati il dispositivo-assoluto--percorso del file nella proprietà `fullPath` di oggetti della `voce`. In genere questi percorsi si sarebbe simile
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Questi percorsi sono stati anche restituiti dal metodo `toURL()` degli oggetti `Entry`.
+
+Con v 1.0.0, l'attributo `fullPath` è il percorso del file, *rispetto alla radice del filesystem HTML*. Così, i percorsi sopra sarebbe ora sia rappresentato da un oggetto `FileEntry` con un `fullPath` di
+
+ /path/to/file
+
+
+Se l'applicazione funziona con dispositivo-assoluto-percorsi, e precedentemente recuperato quei percorsi attraverso la proprietà `fullPath` della `voce` oggetti, è necessario aggiornare il codice per utilizzare `entry.toURL()` invece.
+
+Per indietro la compatibilità, il metodo `resolveLocalFileSystemURL()` verrà accettare un dispositivo-assoluto-percorso e restituirà un oggetto di `entrata` corrispondente ad essa, fintanto che il file esiste all'interno del filesystem la `temporanea` o `permanente`.
+
+Questo particolare è stato un problema con il plugin di trasferimento File, che in precedenza utilizzati percorsi-dispositivo-assoluto (e ancora può accoglierli). Esso è stato aggiornato per funzionare correttamente con gli URL di FileSystem, così sostituendo `entry.fullPath` con `entry.toURL()` dovrebbe risolvere eventuali problemi ottenendo quel plugin per lavorare con i file nel dispositivo.
+
+In v 1.1.0 il valore restituito di `toURL()` è stato cambiato (vedere \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) per restituire un URL assoluto 'file://'. ove possibile. Per assicurare un ' cdvfile:'-URL, è possibile utilizzare `toInternalURL()` ora. Questo metodo restituirà ora filesystem URL del modulo
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+che può essere utilizzato per identificare univocamente il file.
+
+## Elenco dei codici di errore e significati
+
+Quando viene generato un errore, uno dei seguenti codici da utilizzare.
+
+| Codice | Costante |
+| ------:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Configurare il Plugin (opzionale)
+
+Il set di filesystem disponibili può essere configurato per ogni piattaforma. Sia iOS che Android riconoscere un Tag nel `file config. xml` che nomina il filesystem per essere installato. Per impostazione predefinita, tutte le radici del file system sono abilitate.
+
+
+
+
+
+### Android
+
+* `files`: directory di archiviazione di file interno dell'applicazione
+* `files-external`: directory di archiviazione dell'applicazione file esterno
+* `sdcard`: la directory di archiviazione di file esterni globale (questa è la radice della scheda SD, se uno è installato). È necessario disporre dell'autorizzazione `android.permission.WRITE_EXTERNAL_STORAGE` utilizzare questo.
+* `cache`: la cache interna directory applicazione
+* `cache-external`: directory di cache esterna dell'applicazione
+* `root`: il dispositivo intero filesystem
+
+Android supporta anche un filesystem speciale denominato "documenti", che rappresenta una sottodirectory "/ documenti /" all'interno del filesystem "files".
+
+### iOS
+
+* `library`: la directory dell'applicazione libreria
+* `documents`: la directory dell'applicazione documenti
+* `cache`: la Cache directory applicazione
+* `bundle`: bundle dell'applicazione; la posizione dell'app sul disco (sola lettura)
+* `root`: il dispositivo intero filesystem
+
+Per impostazione predefinita, la directory di libreria e documenti può essere sincronizzata a iCloud. È anche possibile richiedere due filesystem aggiuntivi, `library-nosync` e `documents-nosync`, che rappresentano una speciale directory non sincronizzati entro il `/Library` o filesystem `/Documents`.
diff --git a/plugins/cordova-plugin-file/doc/it/plugins.md b/plugins/cordova-plugin-file/doc/it/plugins.md
new file mode 100644
index 0000000..d3f1465
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/it/plugins.md
@@ -0,0 +1,101 @@
+
+
+# Note per gli sviluppatori di plugin
+
+Queste note sono destinate principalmente per gli sviluppatori di Android e iOS che vogliono scrivere plugin quale interfaccia con il sistema di file utilizzando il File plugin.
+
+## Lavorando con URL di sistema file di Cordova
+
+Dalla versione 1.0.0, questo plugin ha utilizzato gli URL con un `cdvfile` schema per tutte le comunicazioni oltre il ponte, piuttosto che esporre i percorsi del file system di dispositivo raw a JavaScript.
+
+Sul lato JavaScript, questo significa che gli oggetti FileEntry e DirectoryEntry dispongano di un attributo fullPath che è relativo alla directory principale del sistema di file HTML. Se API JavaScript del vostro plugin accetta un oggetto FileEntry o DirectoryEntry, è necessario chiamare `.toURL()` su quell'oggetto prima di passarlo attraverso il ponte in codice nativo.
+
+### Conversione cdvfile: / / URL ai percorsi fileystem
+
+Plugin che hanno bisogno di scrivere il filesystem può essere necessario convertire un URL di sistema del file ricevuto in un percorso effettivo filesystem. Ci sono diversi modi di fare questo, a seconda della piattaforma nativa.
+
+È importante ricordare che non tutti i `cdvfile://` URL sono mappabili ai veri file sul dispositivo. Alcuni URL può riferirsi a beni sul dispositivo che non sono rappresentate da file, o possono anche fare riferimento a risorse remote. A causa di queste possibilità, plugin dovrebbe sempre verificare se ottengono un risultato significativo indietro quando si tenta di convertire gli URL in percorsi.
+
+#### Android
+
+Su Android, il metodo più semplice per convertire un `cdvfile://` URL a un percorso di file System è quello di utilizzare `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`dispone di diversi metodi che è possono gestire `cdvfile://` URL:
+
+ webView è un membro del Plugin classe CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ Ottenere un URL file:/// che rappresenta questo file sul dispositivo, / / o lo stesso URL invariata se non può essere mappato a un file Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+È anche possibile utilizzare direttamente il File plugin:
+
+ importazione org.apache.cordova.file.FileUtils;
+ importazione org.apache.cordova.file.FileSystem;
+ importazione java.net.MalformedURLException;
+
+ Ottenere il File plugin dal gestore plugin FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ Dato un URL, ottenere un percorso per esso prova {String path = filePlugin.filesystemPathForURL(cdvfileURL);}} catch (MalformedURLException e) {/ / l'url del file System non è stato riconosciuto}
+
+
+Convertire da un percorso a un `cdvfile://` URL:
+
+ importazione org.apache.cordova.file.LocalFilesystemURL;
+
+ Ottenere un oggetto LocalFilesystemURL per un percorso di dispositivo, / / oppure null se non può essere rappresentata come un URL di cdvfile.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ Ottenere la rappresentazione di stringa dell'URL oggetto String cdvfileURL = url.toString();
+
+
+Se il vostro plugin crea un file e si desidera restituire un oggetto FileEntry per esso, utilizzare il File plugin:
+
+ Restituire una struttura JSON appropriato per restituire a JavaScript, / / o null se questo file non è rappresentabile come un URL di cdvfile.
+ Voce di JSONObject = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+Cordova su iOS non utilizza lo stesso `CordovaResourceApi` concetto come Android. Su iOS, si dovrebbe utilizzare il plugin File per convertire tra URL e percorsi di file System.
+
+ Ottenere un oggetto CDVFilesystem URL da una stringa CDVFilesystemURL * url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ Ottenere un percorso per l'oggetto URL, o zero se non può essere mappato a un percorso di file NSString * = [filePlugin filesystemPathForURL:url];
+
+
+ Ottenere un oggetto CDVFilesystem URL per un percorso di dispositivo, o / / nullo se non può essere rappresentata come un URL di cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ Ottenere la rappresentazione di stringa dell'URL oggetto NSString * cdvfileURL = [absoluteString url];
+
+
+Se il vostro plugin crea un file e si desidera restituire un oggetto FileEntry per esso, utilizzare il File plugin:
+
+ Ottenere un oggetto CDVFilesystem URL per un percorso di dispositivo, o / / nullo se non può essere rappresentata come un URL di cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ Ottenere una struttura per tornare alla voce JavaScript NSDictionary * = [filePlugin makeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+In JavaScript, per ottenere un `cdvfile://` URL da un oggetto FileEntry o DirectoryEntry, semplicemente chiamare `.toURL()` su di esso:
+
+ var cdvfileURL = entry.toURL();
+
+
+Nei gestori di risposta del plugin, per convertire da una struttura FileEntry restituita in un oggetto reale di voce, il codice del gestore dovrebbe importare il File plugin e creare un nuovo oggetto:
+
+ creare la voce appropriata a voce oggetto var;
+ Se (entryStruct.isDirectory) {voce = new DirectoryEntry (entryStruct.name, entryStruct.fullPath, nuovo FileSystem(entryStruct.filesystemName));} altro {voce = FileEntry nuovo (entryStruct.name, entryStruct.fullPath, nuovo FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/ja/README.md b/plugins/cordova-plugin-file/doc/ja/README.md
new file mode 100644
index 0000000..96e8ff0
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ja/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+このプラグインは、デバイス上のファイルへの読み取り/書き込みアクセスを許可するファイル API を実装します。
+
+このプラグインを含む、いくつかの仕様に基づいています:、HTML5 File API の
+
+(今は亡き) ディレクトリとシステムは、最新の拡張機能: プラグインのコードのほとんどはときに、以前の仕様に書かれていたが現在は:
+
+FileWriter 仕様も実装しています:
+
+使用法を参照してください HTML5 岩 ' 優秀な[ファイルシステム記事](http://www.html5rocks.com/en/tutorials/file/filesystem/)。
+
+他のストレージ オプションの概要については、コルドバの[ストレージ ・ ガイド](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html)を参照してください。.
+
+このプラグインでは、グローバル `cordova.file` オブジェクトを定義します。
+
+グローバル スコープではあるがそれがないまで `deviceready` イベントの後です。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## インストール
+
+ cordova plugin add cordova-plugin-file
+
+
+## サポートされているプラットフォーム
+
+ * アマゾン火 OS
+ * アンドロイド
+ * ブラックベリー 10
+ * Firefox の OS
+ * iOS
+ * Windows Phone 7 と 8 *
+ * Windows 8 *
+ * Windows*
+ * ブラウザー
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## ファイルを保存する場所
+
+V1.2.0、現在重要なファイル システム ディレクトリへの Url を提供しています。 各 URL はフォーム *file:///path/to/spot/* で、`window.resolveLocalFileSystemURL()` を使用する `DirectoryEntry` に変換することができます。.
+
+ * `cordova.file.applicationDirectory`-読み取り専用のディレクトリは、アプリケーションがインストールされています。(*iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+ * `cordova.file.applicationStorageDirectory`-アプリケーションのサンド ボックス; のルート ディレクトリiOS でこの場所が読み取り専用 (特定のサブディレクトリが [のような `/Documents` ] は、読み取り/書き込み)。 内に含まれるすべてのデータは、アプリケーションにプライベートです。 ( *iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+ * `cordova.file.dataDirectory`内部メモリを使用して、アプリケーションのサンド ボックス内で永続なプライベート データ ストレージ (外部メモリを使用する必要がある場合使用して Android 上で `.externalDataDirectory` )。 IOS は、このディレクトリは iCloud と同期されません (使用する `.syncedDataDirectory` )。 (*iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+ * `cordova.file.cacheDirectory`-キャッシュされたデータ ファイルやアプリに簡単に再作成できる任意のファイルのディレクトリ。 ストレージ デバイスが不足したときに、OS がこれらのファイルを削除可能性があります、それにもかかわらず、アプリはここにファイルを削除する OS に依存しないでください。 (*iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`外部ストレージのアプリケーション領域。(*アンドロイド*)
+
+ * `cordova.file.externalDataDirectory`-外部ストレージ上のアプリ固有のデータ ファイルを配置する場所。(*アンドロイド*)
+
+ * `cordova.file.externalCacheDirectory`外部ストレージにアプリケーション キャッシュ。(*アンドロイド*)
+
+ * `cordova.file.externalRootDirectory`-外部ストレージ (SD カード) ルート。(*アンドロイド*、*ブラックベリー 10*)
+
+ * `cordova.file.tempDirectory`-OS をクリアすることができます temp ディレクトリが。 このディレクトリ; オフに OS に依存しません。アプリが常に該当するファイルを削除します。 (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-(例えば iCloud) に同期する必要がありますアプリケーション固有のファイルを保持します。(*iOS*)
+
+ * `cordova.file.documentsDirectory`-ファイル、アプリケーションにプライベートは他のアプリケーション (Office ファイルなど) を意味です。(*iOS*)
+
+ * `cordova.file.sharedDirectory`すべてのアプリケーション (*ブラックベリー 10*にグローバルに使用できるファイル)
+
+## ファイル ・ システム ・ レイアウト
+
+技術的に実装の詳細、非常にどのように `cordova.file.*` プロパティは、実際のデバイス上の物理パスにマップを知っておくと便利することができます。
+
+### iOS ファイル システムのレイアウト
+
+| デバイス ・ パス | `cordova.file.*` | `iosExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | 同期 | プライベート |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:--------:|:---------:|:------------:|:------:|:------:|
+| `/var/モバイル/アプリケーション/< UUID >/` | applicationStorageDirectory | - | r | N/A | N/A | N/A | はい |
+| `appname.app/` | ディレクトリ | バンドル | r | N/A | N/A | N/A | はい |
+| `www/` | - | - | r | N/A | N/A | N/A | はい |
+| `Documents/` | documentsDirectory | ドキュメント | r/w | はい | いいえ | はい | はい |
+| `NoCloud/` | - | ドキュメント nosync | r/w | はい | いいえ | いいえ | はい |
+| `Library` | - | ライブラリ | r/w | はい | いいえ | はいですか? | はい |
+| `NoCloud/` | dataDirectory | ライブラリ nosync | r/w | はい | いいえ | いいえ | はい |
+| `Cloud/` | syncedDataDirectory | - | r/w | はい | いいえ | はい | はい |
+| `Caches/` | cacheDirectory | キャッシュ | r/w | はい * | はい**\* | いいえ | はい |
+| `tmp/` | tempDirectory | - | r/w | いいえ** | はい**\* | いいえ | はい |
+
+\ * アプリ再起動やアップグレード、永続化ファイルしますが、OS を希望するたびに、このディレクトリを削除することができます。アプリは削除可能性があります任意のコンテンツを再現することができるはず。
+
+**ファイルはアプリ再起動の間続くことがありますが、この動作に依存しないでください。 ファイルは、更新を維持するは保証されません。 アプリが該当する場合このディレクトリからファイルを削除する必要があります、これらのファイルが削除されるとき (または場合でも)、OS は保証しません。
+
+**\ * OS はそれ、必要だと感じているときにこのディレクトリの内容を消去可能性があります、これに依存しないようにします。 この適切なディレクトリに、アプリケーションをオフにする必要があります。
+
+### 人造人間ファイル ・ システム ・ レイアウト
+
+| デバイス ・ パス | `cordova.file.*` | `AndroidExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:--------:|:--------:|:---------:|:------:|
+| `file:///android_asset/` | ディレクトリ | | r | N/A | N/A | はい |
+| `/データ/データ/< app id >/` | applicationStorageDirectory | - | r/w | N/A | N/A | はい |
+| `cache` | cacheDirectory | キャッシュ | r/w | はい | はい\ * | はい |
+| `files` | dataDirectory | ファイル | r/w | はい | いいえ | はい |
+| `Documents` | | ドキュメント | r/w | はい | いいえ | はい |
+| `< sd カード >/` | externalRootDirectory | sd カード | r/w | はい | いいえ | いいえ |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | はい | いいえ | いいえ |
+| `cache` | externalCacheDirectry | 外部キャッシュ | r/w | はい | いいえ** | いいえ |
+| `files` | externalDataDirectory | 外部ファイル | r/w | はい | いいえ | いいえ |
+
+\ * OS は定期的にこのディレクトリを消去可能性がありますが、この動作に依存しないでください。 アプリケーションの必要に応じてこのディレクトリの内容をオフにします。 ユーザーは手動でキャッシュを削除する必要があります、このディレクトリの内容が削除されます。
+
+** OS はこのディレクトリを自動的にはクリアされません内容を自分で管理する責任があります。 ユーザは手動でキャッシュを消去する必要があります、ディレクトリの内容が削除されます。
+
+**注**: 外部記憶装置をマウントできない場合は、`cordova.file.external*` プロパティを `null`.
+
+### ブラックベリー 10 ファイル ・ システム ・ レイアウト
+
+| デバイス ・ パス | `cordova.file.*` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート |
+|:----------------------------------------------------------- |:--------------------------- |:--------:|:--------:|:---------:|:------:|
+| `file:///accounts/1000/appdata/< app id >/` | applicationStorageDirectory | r | N/A | N/A | はい |
+| `app/native` | ディレクトリ | r | N/A | N/A | はい |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | いいえ | はい | はい |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | はい | いいえ | はい |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | はい | いいえ | いいえ |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | はい | いいえ | いいえ |
+
+*注*: すべてのパスは/accounts/1000-enterprise 基準に境界を動作するようにアプリケーションを展開するとき。
+
+## Android の癖
+
+### Android の永続的なストレージの場所
+
+Android のデバイスに永続的なファイルを格納する複数の有効な場所があります。 さまざまな可能性について広範な議論のための [このページ](http://developer.android.com/guide/topics/data/data-storage.html) を参照してください。
+
+以前のバージョンのプラグインは、デバイスの SD カード (または同等のストレージ パーティション) マウントされていたと主張したかどうかに基づいて、起動時に一時と永続的なファイルの場所を選ぶでしょう。 SD カードがマウントされている場合、または大規模な内部ストレージ パーティションが利用可能な場合 (ようネクサス デバイス上) し、永続的なファイルは、その領域のルートに格納されます。 これはすべての Cordova アプリ見ることができる利用可能なファイルのすべてのカードに意味しました。
+
+SD カードがない場合、以前のバージョンがデータを格納する `/data/data/`、お互いからアプリを分離するが、まだ原因可能性がありますユーザー間で共有するデータ。
+
+内部ファイルの保存場所やアプリケーションの `config.xml` ファイルに優先順位を持つ以前のロジックを使用してファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。
+
+
+
+
+
+
+この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。
+
+アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを彼らの装置によって、以前に保存されたファイルにアクセスすることができることがあることを意味する「内部」に場所をスイッチングします。
+
+アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`内部` 設定一般的に推奨されます。
+
+### /Android_asset の低速の再帰的な操作
+
+アセット ディレクトリの一覧表示は、人造人間本当に遅いです。 それをスピードアップすることができます`src/android/build-extras.gradle`を android プロジェクトのルートに追加することによって、最大 (また cordova-android@4.0.0 が必要ですまたはそれ以上)。
+
+## iOS の癖
+
+ * `cordova.file.applicationStorageDirectory`読み取り専用;ルート ディレクトリ内のファイルを保存しようは失敗します。 他の 1 つを使用して `cordova.file.*` iOS のため定義されているプロパティ (のみ `applicationDirectory` と `applicationStorageDirectory` は読み取り専用)。
+ * `FileReader.readAsText(blob, encoding)`
+ * `encoding`パラメーターはサポートされていませんし、utf-8 エンコーディングが常に有効です。
+
+### iOS の永続的なストレージの場所
+
+IOS デバイスに永続的なファイルを格納する 2 つの有効な場所がある: ドキュメントとライブラリのディレクトリ。 プラグインの以前のバージョンは、唯一のこれまでドキュメント ディレクトリに永続的なファイルを格納されます。 これは、ディレクトリの目的は、輸出のための完全なドキュメントを作成するのではなくなかったがしばしば意図されていたり、特に多数の小さいファイルを処理するアプリケーションの場合、iTunes に表示されているすべてのアプリケーションのファイルを作るの副作用があった。
+
+ドキュメントまたはアプリケーションの `config.xml` ファイルに優先順位のライブラリ ディレクトリにファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。
+
+
+
+
+
+
+この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。
+
+アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを以前に保存されたファイルにアクセスすることができるだろうことを意味する `Library` に場所をスイッチングします。
+
+アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`Library` 設定一般的に推奨されます。
+
+## Firefox OS 癖
+
+ファイル システム API Firefox OS でネイティブ サポートされていないと、indexedDB の上にシムとして実装されています。
+
+ * 空でないディレクトリを削除するときに失敗しません
+ * ディレクトリのメタデータをサポートしていません
+ * 方法 `copyTo` と `moveTo` ディレクトリをサポートしていません
+
+次のデータ パスがサポートされています: * `applicationDirectory` - `xhr` を使用して、アプリケーションと共にパッケージ化されるローカル ファイルを取得します。 * `dataDirectory` - 永続的なアプリケーション固有のデータ ファイル。 * `cacheDirectory` - アプリケーションの再起動後も維持する必要がありますキャッシュ ファイル (アプリはここにファイルを削除する OS に依存しないでください)。
+
+## ブラウザーの癖
+
+### 共通の癖と発言
+
+ * 各ブラウザーはサンド ボックス化されたファイルシステムを使用します。IE と Firefox IndexedDB をベースとして使用します。すべてのブラウザーは、パスにディレクトリの区切り記号としてスラッシュを使用します。
+ * ディレクトリ エントリは連続して作成されなければなりません。 たとえば、コール `fs.root.getDirectory ('dir1 dir2'、{create:true}、successCallback、解り)` dir1 が存在しなかった場合は失敗します。
+ * プラグインは、永続的なストレージ アプリケーションの最初の起動時に使用するユーザーのアクセス許可を要求します。
+ * プラグインは、`cdvfile://localhost` (ローカル リソース) をサポートしているだけです。すなわち外部リソースは、`cdvfile` を介してサポートされていません.
+ * プラグインに [制限」のファイル システム API の 8.3 命名規則](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions) に従っていません。.
+ * Blob およびファイル ' `close` 関数はサポートされていません。
+ * `FileSaver` と `BlobBuilder` このプラグインでサポートされていないスタブを持っていません。
+ * プラグインは、`requestAllFileSystems` をサポートしません。この関数は、仕様で行方不明にも。
+ * ディレクトリ内のエントリを使用すると削除されません `create: true` 既存ディレクトリのフラグ。
+ * コンス トラクターで作成されたファイルはサポートされていません。代わりに entry.file メソッドを使用する必要があります。
+ * 各ブラウザーは blob URL 参照の独自のフォームを使用します。
+ * `readAsDataURL` 関数はサポートされてがクロムメッキで mediatype エントリ名の拡張子によって異なります、IE でメディアの種類は、常に空 (`text-plain` に従って、仕様と同じである)、Firefox でメディアの種類は常に `アプリケーションまたはオクテット-ストリーム`。 たとえば、コンテンツが場合 `abcdefg` し Firefox を返します `データ: アプリケーション/オクテット ストリーム、base64、YWJjZGVmZw = =`、すなわちを返します `データ:; base64、YWJjZGVmZw = =`、クロムを返します `データ: < エントリ名の拡張子によって mediatype >; base64、YWJjZGVmZw = =`.
+ * `toInternalURL` フォーム `file:///persistent/path/to/entry` (Firefox、IE) のパスを返します。 クロムの `cdvfile://localhost/persistent/file` フォームのパスを返します.
+
+### クロムの癖
+
+ * デバイスの準備ができているイベント後クローム ファイルシステムはすぐに準備ができています。回避策としては `filePluginIsReady` イベントにサブスクライブできます。例:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+`window.isFilePluginReadyRaised` 関数を使用して、イベントが既に発生したかどうかを確認できます。 -Chrome に window.requestFileSystem 一時と永続的なファイル ・ システムのクォータの制限はありません。 -クロム内の永続ストレージを増加する `window.initPersistentFileSystem` メソッドを呼び出す必要があります。 永続的な記憶域のクォータは、既定では 5 MB です。 クロムが必要です `--許可-ファイル-アクセス--ファイルから` `file:///` プロトコル経由でサポート API に引数を実行します。 -`ファイル` オブジェクト フラグを使用する場合ない変更されます `{create:true}` 既存の `エントリ` を取得するとき。 -イベント `cancelable` プロパティを設定するクロムの場合は true。 これは [仕様](http://dev.w3.org/2009/dap/file-system/file-writer.html) に反して。 -クロムメッキで `網` 関数を返します `ファイルシステム:`-アプリケーションのホストによってパスのプレフィックスします。 たとえば、`filesystem:file:///persistent/somefile.txt`、`filesystem:http://localhost:8080/persistent/somefile.txt`。 -`toURL` の関数の結果にはディレクトリ エントリ場合末尾にスラッシュが含まれていません。 クロムは、スラッシュ後塵 url を持つディレクトリが正しく解決されるも。 -`resolveLocalFileSystemURL` メソッドは、受信 `url` が `ファイルシステム` のプレフィックスが必要です。 たとえば、`resolveLocalFileSystemURL` の `url` パラメーター フォーム `filesystem:file:///persistent/somefile.txt` で人造人間フォーム `file:///persistent/somefile.txt` とは対照的にする必要があります。 -廃止された `toNativeURL` 関数はサポートされていません、スタブはありません。 -`setMetadata` 関数は、仕様に記載されていないありサポートされていません。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた SYNTAX_ERR(code: 8) の非実在しないファイルシステムの依頼を。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた PATH_EXISTS_ERR(code: 12)、排他的なファイルまたはディレクトリを作成しようとするが既に存在します。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NO_MODIFICATION_ALLOWED_ERR(code: 6) ルート ・ ファイル ・ システムで removeRecursively を呼び出すをしようとして。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NOT_FOUND_ERR(code: 1) [moveto] ディレクトリが存在しないをしようとして。
+
+### IndexedDB ベース インプレ癖 (Firefox と IE)
+
+ * `.` `です。` はサポートされていません。
+ * IE は `file:///` をサポートしていません-モード;ホスト モードのみがサポートされている (http://localhost:xxxx) です。
+ * Firefox のファイルシステムのサイズは無制限ですが各 50 MB の拡張機能がユーザーのアクセス許可を要求します。 IE10 は最大 10 mb の複合 AppCache と IndexedDB を求めず、サイトごとに 250 mb の最大値まで増加を許可するかどうかをたずねられますそのレベルに当ればファイルシステムの実装で使用することができます。 `RequestFileSystem` 関数の `size` パラメーターは、Firefox と IE のファイルシステムには影響しません。
+ * `readAsBinaryString` 関数の仕様に記載されていない、IE でサポートされていないと、スタブを持っていません。
+ * `file.type` は、常に null です。
+ * 削除された DirectoryEntry インスタンスのコールバックの結果を使用してエントリを作成しないでください。それ以外の場合は、'ハンギングのエントリ' が表示されます。
+ * ちょうど書かれていた、ファイルを読むことができます前にこのファイルの新しいインスタンスを取得する必要があります。
+ * `setMetadata` 関数は、仕様に記載されていない `modificationTime` フィールド変更のみをサポートします。
+ * `copyTo` と `moveTo` 関数ディレクトリをサポートしていません。
+ * ディレクトリのメタデータはサポートされていません。
+ * 両方の Entry.remove と directoryEntry.removeRecursively は空でないディレクトリを削除するときを失敗しない - 削除されるディレクトリ コンテンツと共にを掃除している代わりに。
+ * `abort` し、`truncate` 機能はサポートされていません。
+ * 進行状況イベントは起動しません。たとえば、このハンドラーがない実行されます。
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## ノートをアップグレードします。
+
+このプラグインのデベロッパー、公開された仕様に合うように、`認証` と `DirectoryEntry` の構造が変更されました。
+
+プラグインの前 (pre 1.0.0) バージョンはデバイス絶対ファイル場所 `エントリ` オブジェクトの `fullPath` プロパティに格納されます。これらのパスはようになります通常
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+これらのパスはまた `Entry` オブジェクトの `toURL()` メソッドによって返されます。
+
+デベロッパー、`fullPath` 属性は *HTML ファイルシステムのルートに対する相対パス* のファイルへのパス。 したがって、上記のパスは今両方の `fullPath` と `FileEntry` オブジェクトで表される
+
+ /path/to/file
+
+
+デバイス絶対パスとアプリケーション動作以前 `Entry` オブジェクトの `fullPath` プロパティを使用してこれらのパスを取得した場合は、代わりに `entry.toURL()` を使用するコードを更新する必要があります。
+
+下位互換性、`resolveLocalFileSystemURL()` メソッドは、デバイス絶対パスを受け入れるし、は、`TEMPORARY` または `PERSISTENT` ファイル ・ システム内でそのファイルが存在する限り、それに対応する `Entry` オブジェクトを返します。
+
+これは特に以前デバイス絶対パスを使用してファイル転送のプラグインで問題となっている (そしてまだそれらを受け入れることができます)。 それがデバイス上のファイルで動作するプラグインを得る問題を解決する必要があります `entry.toURL()` で `entry.fullPath` を置き換えるので、ファイルシステムの Url で正常に動作にアップデートされました。
+
+V1.1.0 の `toURL()` の戻り値に変更されました (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) を参照) を絶対 'file://' で始まる URL を返します。 可能な限り。 確保するために、' cdvfile:'-`toInternalURL()` を今すぐ使用できます URL。 このメソッドは、フォームのファイルシステムの Url を返します今
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+これはファイルを一意に識別するために使用できます。
+
+## エラー コードと意味のリスト
+
+エラーがスローされると、次のコードのいずれかが使用されます。
+
+| コード | 定数 |
+| ---:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## (省略可能) プラグインを構成します。
+
+利用可能なファイルシステムのセットは構成されたプラットフォームをすることができます。IOS と Android の両方を認識します。 タグ `config.xml` をインストールするファイルシステムの名前します。既定では、すべてのファイル システムのルートが有効になります。
+
+
+
+
+
+### アンドロイド
+
+ * `files`: アプリケーションの内部ファイルのストレージ ディレクトリ
+ * `files-external`: アプリケーションの外部のファイルのストレージ ディレクトリ
+ * `sdcard`:、グローバル外部ストレージ ディレクトリをファイル (これは SD カードのルートがインストールされている場合)。 これを使用するには、`android.permission.WRITE_EXTERNAL_STORAGE` 権限が必要です。
+ * `cache`: アプリケーションの内部キャッシュ ディレクトリ
+ * `cache-external`: 外部キャッシュのアプリケーションのディレクトリ
+ * `root`: デバイス全体のファイルシステム
+
+アンドロイドを「ファイル」ファイルシステム内の"ドキュメント/"サブディレクトリを表す"ドキュメント"という名前の特殊なファイルシステムもサポートしています。
+
+### iOS
+
+ * `library`: ライブラリのアプリケーションのディレクトリ
+ * `documents`: ドキュメントのアプリケーションのディレクトリ
+ * `cache`: キャッシュのアプリケーションのディレクトリ
+ * `bundle`: アプリケーションバンドル;アプリ自体 (読み取りのみ) ディスク上の場所
+ * `root`: デバイス全体のファイルシステム
+
+既定では、ライブラリとドキュメント ディレクトリを iCloud に同期できます。 2 つの追加のファイルシステム、`library-nosync` および `documents-nosync` を表す、特別な非同期ディレクトリ内を要求することもできます、`/Library` または `Documents/` ファイルシステム。
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/ja/index.md b/plugins/cordova-plugin-file/doc/ja/index.md
new file mode 100644
index 0000000..57fb7d2
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ja/index.md
@@ -0,0 +1,338 @@
+
+
+# cordova-plugin-file
+
+このプラグインは、デバイス上のファイルへの読み取り/書き込みアクセスを許可するファイル API を実装します。
+
+このプラグインを含む、いくつかの仕様に基づいています:、HTML5 File API の
+
+(今は亡き) ディレクトリとシステムは、最新の拡張機能: プラグインのコードのほとんどはときに、以前の仕様に書かれていたが現在は:
+
+FileWriter 仕様も実装しています:
+
+使用法を参照してください HTML5 岩 ' 優秀な[ファイルシステム記事][1]。
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+他のストレージ オプションの概要については、コルドバの[ストレージ ・ ガイド][2]を参照してください。.
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+このプラグインでは、グローバル `cordova.file` オブジェクトを定義します。
+
+グローバル スコープではあるがそれがないまで `deviceready` イベントの後です。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## インストール
+
+ cordova plugin add cordova-plugin-file
+
+
+## サポートされているプラットフォーム
+
+* アマゾン火 OS
+* アンドロイド
+* ブラックベリー 10
+* Firefox の OS
+* iOS
+* Windows Phone 7 と 8 *
+* Windows 8 *
+* ブラウザー
+
+* *`FileReader.readAsArrayBuffer` も `FileWriter.write(blob)` もこれらのプラットフォームはサポートしていません*。
+
+## ファイルを保存する場所
+
+V1.2.0、現在重要なファイル システム ディレクトリへの Url を提供しています。 各 URL はフォーム *file:///path/to/spot/* で、`window.resolveLocalFileSystemURL()` を使用する `DirectoryEntry` に変換することができます。.
+
+* `cordova.file.applicationDirectory`-読み取り専用のディレクトリは、アプリケーションがインストールされています。(*iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+* `cordova.file.applicationStorageDirectory`-アプリケーションのサンド ボックス; のルート ディレクトリiOS でこの場所が読み取り専用 (特定のサブディレクトリが [のような `/Documents` ] は、読み取り/書き込み)。 内に含まれるすべてのデータは、アプリケーションにプライベートです。 ( *iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+* `cordova.file.dataDirectory`内部メモリを使用して、アプリケーションのサンド ボックス内で永続なプライベート データ ストレージ (外部メモリを使用する必要がある場合使用して Android 上で `.externalDataDirectory` )。 IOS は、このディレクトリは iCloud と同期されません (使用する `.syncedDataDirectory` )。 (*iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+* `cordova.file.cacheDirectory`-キャッシュされたデータ ファイルやアプリに簡単に再作成できる任意のファイルのディレクトリ。 ストレージ デバイスが不足したときに、OS がこれらのファイルを削除可能性があります、それにもかかわらず、アプリはここにファイルを削除する OS に依存しないでください。 (*iOS*、*アンドロイド*、*ブラックベリー 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`外部ストレージのアプリケーション領域。(*アンドロイド*)
+
+* `cordova.file.externalDataDirectory`-外部ストレージ上のアプリ固有のデータ ファイルを配置する場所。(*アンドロイド*)
+
+* `cordova.file.externalCacheDirectory`外部ストレージにアプリケーション キャッシュ。(*アンドロイド*)
+
+* `cordova.file.externalRootDirectory`-外部ストレージ (SD カード) ルート。(*アンドロイド*、*ブラックベリー 10*)
+
+* `cordova.file.tempDirectory`-OS をクリアすることができます temp ディレクトリが。 このディレクトリ; オフに OS に依存しません。アプリが常に該当するファイルを削除します。 (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-(例えば iCloud) に同期する必要がありますアプリケーション固有のファイルを保持します。(*iOS*)
+
+* `cordova.file.documentsDirectory`-ファイル、アプリケーションにプライベートは他のアプリケーション (Office ファイルなど) を意味です。(*iOS*)
+
+* `cordova.file.sharedDirectory`すべてのアプリケーション (*ブラックベリー 10*にグローバルに使用できるファイル)
+
+## ファイル ・ システム ・ レイアウト
+
+技術的に実装の詳細、非常にどのように `cordova.file.*` プロパティは、実際のデバイス上の物理パスにマップを知っておくと便利することができます。
+
+### iOS ファイル システムのレイアウト
+
+| デバイス ・ パス | `cordova.file.*` | `iosExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | 同期 | プライベート |
+|:------------------------------------ |:--------------------------- |:--------------------- |:--------:|:--------:|:----------:|:------:|:------:|
+| `/var/モバイル/アプリケーション/< UUID >/` | applicationStorageDirectory | - | r | N/A | N/A | N/A | はい |
+| `appname.app/` | ディレクトリ | バンドル | r | N/A | N/A | N/A | はい |
+| `www/` | - | - | r | N/A | N/A | N/A | はい |
+| `Documents/` | documentsDirectory | ドキュメント | r/w | はい | いいえ | はい | はい |
+| `NoCloud/` | - | ドキュメント nosync | r/w | はい | いいえ | いいえ | はい |
+| `Library` | - | ライブラリ | r/w | はい | いいえ | はいですか? | はい |
+| `NoCloud/` | dataDirectory | ライブラリ nosync | r/w | はい | いいえ | いいえ | はい |
+| `Cloud/` | syncedDataDirectory | - | r/w | はい | いいえ | はい | はい |
+| `Caches/` | cacheDirectory | キャッシュ | r/w | はい * | はい * * *| | いいえ | はい |
+| `tmp/` | tempDirectory | - | r/w | いいえ * * | はい * * *| | いいえ | はい |
+
+* アプリを再起動し、アップグレードとの間でファイルを保持が、OS を希望するたびにこのディレクトリを削除することができます。アプリを削除可能性があります任意のコンテンツを再作成することができる必要があります。
+
+* * ファイル アプリケーション再起動を渡って続くことがありますが、この動作に依存しないでください。 ファイルは、更新を維持するは保証されません。 アプリが該当する場合このディレクトリからファイルを削除する必要があります、これらのファイルが削除されるとき (または場合でも)、OS は保証しません。
+
+* * *| OS はそれ、必要だと感じているときにこのディレクトリの内容を消去可能性がありますが、これに依存しません。 この適切なディレクトリに、アプリケーションをオフにする必要があります。
+
+### 人造人間ファイル ・ システム ・ レイアウト
+
+| デバイス ・ パス | `cordova.file.*` | `AndroidExtraFileSystems` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート |
+|:--------------------------------- |:----------------------------------- |:------------------------- |:--------:|:--------:|:---------:|:------:|
+| `file:///android_asset/` | ディレクトリ | | r | N/A | N/A | はい |
+| `/データ/データ/< app id >/` | applicationStorageDirectory | - | r/w | N/A | N/A | はい |
+| `cache` | cacheDirectory | キャッシュ | r/w | はい | はい * | はい |
+| `files` | dataDirectory | ファイル | r/w | はい | いいえ | はい |
+| `Documents` | | ドキュメント | r/w | はい | いいえ | はい |
+| `< sd カード >/` | externalRootDirectory | sd カード | r/w | はい | いいえ | いいえ |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | はい | いいえ | いいえ |
+| `cache` | externalCacheDirectry | 外部キャッシュ | r/w | はい | いいえ * * | いいえ |
+| `files` | externalDataDirectory | 外部ファイル | r/w | はい | いいえ | いいえ |
+
+* OS このディレクトリを定期的に消去可能性がありますが、この動作に依存しないでください。 アプリケーションの必要に応じてこのディレクトリの内容をオフにします。 ユーザーは手動でキャッシュを削除する必要があります、このディレクトリの内容が削除されます。
+
+* * OS はこのディレクトリは自動的にクリアされません自分でコンテンツを管理するために責任があります。 ユーザは手動でキャッシュを消去する必要があります、ディレクトリの内容が削除されます。
+
+**注**: 外部記憶装置をマウントできない場合は、`cordova.file.external*` プロパティを `null`.
+
+### ブラックベリー 10 ファイル ・ システム ・ レイアウト
+
+| デバイス ・ パス | `cordova.file.*` | r/w ですか? | 永続的なですか? | OS を消去します | プライベート |
+|:------------------------------------------------- |:--------------------------- |:--------:|:--------:|:---------:|:------:|
+| `file:///accounts/1000/appdata/< app id >/` | applicationStorageDirectory | r | N/A | N/A | はい |
+| `app/native` | ディレクトリ | r | N/A | N/A | はい |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | いいえ | はい | はい |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | はい | いいえ | はい |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | はい | いいえ | いいえ |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | はい | いいえ | いいえ |
+
+*注*: すべてのパスは/accounts/1000-enterprise 基準に境界を動作するようにアプリケーションを展開するとき。
+
+## Android の癖
+
+### Android の永続的なストレージの場所
+
+Android のデバイスに永続的なファイルを格納する複数の有効な場所があります。 さまざまな可能性について広範な議論のための [このページ][3] を参照してください。
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+以前のバージョンのプラグインは、デバイスの SD カード (または同等のストレージ パーティション) マウントされていたと主張したかどうかに基づいて、起動時に一時と永続的なファイルの場所を選ぶでしょう。 SD カードがマウントされている場合、または大規模な内部ストレージ パーティションが利用可能な場合 (ようネクサス デバイス上) し、永続的なファイルは、その領域のルートに格納されます。 これはすべての Cordova アプリ見ることができる利用可能なファイルのすべてのカードに意味しました。
+
+SD カードがない場合、以前のバージョンがデータを格納する `/data/data/`、お互いからアプリを分離するが、まだ原因可能性がありますユーザー間で共有するデータ。
+
+内部ファイルの保存場所やアプリケーションの `config.xml` ファイルに優先順位を持つ以前のロジックを使用してファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。
+
+
+
+
+
+
+この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。
+
+アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを彼らの装置によって、以前に保存されたファイルにアクセスすることができることがあることを意味する「内部」に場所をスイッチングします。
+
+アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`内部` 設定一般的に推奨されます。
+
+## iOS の癖
+
+* `cordova.file.applicationStorageDirectory`読み取り専用;ルート ディレクトリ内のファイルを保存しようは失敗します。 他の 1 つを使用して `cordova.file.*` iOS のため定義されているプロパティ (のみ `applicationDirectory` と `applicationStorageDirectory` は読み取り専用)。
+* `FileReader.readAsText(blob, encoding)`
+ * `encoding`パラメーターはサポートされていませんし、utf-8 エンコーディングが常に有効です。
+
+### iOS の永続的なストレージの場所
+
+IOS デバイスに永続的なファイルを格納する 2 つの有効な場所がある: ドキュメントとライブラリのディレクトリ。 プラグインの以前のバージョンは、唯一のこれまでドキュメント ディレクトリに永続的なファイルを格納されます。 これは、ディレクトリの目的は、輸出のための完全なドキュメントを作成するのではなくなかったがしばしば意図されていたり、特に多数の小さいファイルを処理するアプリケーションの場合、iTunes に表示されているすべてのアプリケーションのファイルを作るの副作用があった。
+
+ドキュメントまたはアプリケーションの `config.xml` ファイルに優先順位のライブラリ ディレクトリにファイルを保存するかどうかを選択することが可能です今。 これを行うに、`config.xml` に次の 2 行のいずれかを追加します。
+
+
+
+
+
+
+この行がなければファイル プラグインはデフォルトとして `Compatibility` を使用します。優先タグが存在し、これらの値の 1 つではない場合、アプリケーションは起動しません。
+
+アプリケーションは、ユーザーに以前出荷されている場合、古い (前 1.0) を使用して、このプラグインのバージョンし、永続的なファイルシステムに保存されているファイルには `Compatibility` を設定する必要があります。 自分のアプリケーションをアップグレードする既存のユーザーを以前に保存されたファイルにアクセスすることができるだろうことを意味する `Library` に場所をスイッチングします。
+
+アプリケーションは、新しい、または永続的なファイルシステムにファイルが格納され以前は決して場合、`Library` 設定一般的に推奨されます。
+
+## Firefox OS 癖
+
+ファイル システム API Firefox OS でネイティブ サポートされていないと、indexedDB の上にシムとして実装されています。
+
+* 空でないディレクトリを削除するときに失敗しません
+* ディレクトリのメタデータをサポートしていません
+* 方法 `copyTo` と `moveTo` ディレクトリをサポートしていません
+
+次のデータ パスがサポートされています: * `applicationDirectory` - `xhr` を使用して、アプリケーションと共にパッケージ化されるローカル ファイルを取得します。 * `dataDirectory` - 永続的なアプリケーション固有のデータ ファイル。 * `cacheDirectory` - アプリケーションの再起動後も維持する必要がありますキャッシュ ファイル (アプリはここにファイルを削除する OS に依存しないでください)。
+
+## ブラウザーの癖
+
+### 共通の癖と発言
+
+* 各ブラウザーはサンド ボックス化されたファイルシステムを使用します。IE と Firefox IndexedDB をベースとして使用します。すべてのブラウザーは、パスにディレクトリの区切り記号としてスラッシュを使用します。
+* ディレクトリ エントリは連続して作成されなければなりません。 たとえば、コール `fs.root.getDirectory ('dir1 dir2'、{create:true}、successCallback、解り)` dir1 が存在しなかった場合は失敗します。
+* プラグインは、永続的なストレージ アプリケーションの最初の起動時に使用するユーザーのアクセス許可を要求します。
+* プラグインは、`cdvfile://localhost` (ローカル リソース) をサポートしているだけです。すなわち外部リソースは、`cdvfile` を介してサポートされていません.
+* プラグインに [制限」のファイル システム API の 8.3 命名規則][4] に従っていません。.
+* Blob およびファイル ' `close` 関数はサポートされていません。
+* `FileSaver` と `BlobBuilder` このプラグインでサポートされていないスタブを持っていません。
+* プラグインは、`requestAllFileSystems` をサポートしません。この関数は、仕様で行方不明にも。
+* ディレクトリ内のエントリを使用すると削除されません `create: true` 既存ディレクトリのフラグ。
+* コンス トラクターで作成されたファイルはサポートされていません。代わりに entry.file メソッドを使用する必要があります。
+* 各ブラウザーは blob URL 参照の独自のフォームを使用します。
+* `readAsDataURL` 関数はサポートされてがクロムメッキで mediatype エントリ名の拡張子によって異なります、IE でメディアの種類は、常に空 (`text-plain` に従って、仕様と同じである)、Firefox でメディアの種類は常に `アプリケーションまたはオクテット-ストリーム`。 たとえば、コンテンツが場合 `abcdefg` し Firefox を返します `データ: アプリケーション/オクテット ストリーム、base64、YWJjZGVmZw = =`、すなわちを返します `データ:; base64、YWJjZGVmZw = =`、クロムを返します `データ: < エントリ名の拡張子によって mediatype >; base64、YWJjZGVmZw = =`.
+* `toInternalURL` フォーム `file:///persistent/path/to/entry` (Firefox、IE) のパスを返します。 クロムの `cdvfile://localhost/persistent/file` フォームのパスを返します.
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### クロムの癖
+
+* デバイスの準備ができているイベント後クローム ファイルシステムはすぐに準備ができています。回避策としては `filePluginIsReady` イベントにサブスクライブできます。例:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+`window.isFilePluginReadyRaised` 関数を使用して、イベントが既に発生したかどうかを確認できます。 -Chrome に window.requestFileSystem 一時と永続的なファイル ・ システムのクォータの制限はありません。 -クロム内の永続ストレージを増加する `window.initPersistentFileSystem` メソッドを呼び出す必要があります。 永続的な記憶域のクォータは、既定では 5 MB です。 クロムが必要です `--許可-ファイル-アクセス--ファイルから` `file:///` プロトコル経由でサポート API に引数を実行します。 -`ファイル` オブジェクト フラグを使用する場合ない変更されます `{create:true}` 既存の `エントリ` を取得するとき。 -イベント `cancelable` プロパティを設定するクロムの場合は true。 これは [仕様][5] に反して。 -クロムメッキで `網` 関数を返します `ファイルシステム:`-アプリケーションのホストによってパスのプレフィックスします。 たとえば、`filesystem:file:///persistent/somefile.txt`、`filesystem:http://localhost:8080/persistent/somefile.txt`。 -`toURL` の関数の結果にはディレクトリ エントリ場合末尾にスラッシュが含まれていません。 クロムは、スラッシュ後塵 url を持つディレクトリが正しく解決されるも。 -`resolveLocalFileSystemURL` メソッドは、受信 `url` が `ファイルシステム` のプレフィックスが必要です。 たとえば、`resolveLocalFileSystemURL` の `url` パラメーター フォーム `filesystem:file:///persistent/somefile.txt` で人造人間フォーム `file:///persistent/somefile.txt` とは対照的にする必要があります。 -廃止された `toNativeURL` 関数はサポートされていません、スタブはありません。 -`setMetadata` 関数は、仕様に記載されていないありサポートされていません。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた SYNTAX_ERR(code: 8) の非実在しないファイルシステムの依頼を。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた PATH_EXISTS_ERR(code: 12)、排他的なファイルまたはディレクトリを作成しようとするが既に存在します。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NO_MODIFICATION_ALLOWED_ERR(code: 6) ルート ・ ファイル ・ システムで removeRecursively を呼び出すをしようとして。 -INVALID_MODIFICATION_ERR (コード: 9) の代わりにスローされた NOT_FOUND_ERR(code: 1) [moveto] ディレクトリが存在しないをしようとして。
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### IndexedDB ベース インプレ癖 (Firefox と IE)
+
+* `.` `です。` はサポートされていません。
+* IE は `file:///` をサポートしていません-モード;ホスト モードのみがサポートされている (http://localhost:xxxx) です。
+* Firefox のファイルシステムのサイズは無制限ですが各 50 MB の拡張機能がユーザーのアクセス許可を要求します。 IE10 は最大 10 mb の複合 AppCache と IndexedDB を求めず、サイトごとに 250 mb の最大値まで増加を許可するかどうかをたずねられますそのレベルに当ればファイルシステムの実装で使用することができます。 `RequestFileSystem` 関数の `size` パラメーターは、Firefox と IE のファイルシステムには影響しません。
+* `readAsBinaryString` 関数の仕様に記載されていない、IE でサポートされていないと、スタブを持っていません。
+* `file.type` は、常に null です。
+* 削除された DirectoryEntry インスタンスのコールバックの結果を使用してエントリを作成しないでください。それ以外の場合は、'ハンギングのエントリ' が表示されます。
+* ちょうど書かれていた、ファイルを読むことができます前にこのファイルの新しいインスタンスを取得する必要があります。
+* `setMetadata` 関数は、仕様に記載されていない `modificationTime` フィールド変更のみをサポートします。
+* `copyTo` と `moveTo` 関数ディレクトリをサポートしていません。
+* ディレクトリのメタデータはサポートされていません。
+* 両方の Entry.remove と directoryEntry.removeRecursively は空でないディレクトリを削除するときを失敗しない - 削除されるディレクトリ コンテンツと共にを掃除している代わりに。
+* `abort` し、`truncate` 機能はサポートされていません。
+* 進行状況イベントは起動しません。たとえば、このハンドラーがない実行されます。
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## ノートをアップグレードします。
+
+このプラグインのデベロッパー、公開された仕様に合うように、`認証` と `DirectoryEntry` の構造が変更されました。
+
+プラグインの前 (pre 1.0.0) バージョンはデバイス絶対ファイル場所 `エントリ` オブジェクトの `fullPath` プロパティに格納されます。これらのパスはようになります通常
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+これらのパスはまた `Entry` オブジェクトの `toURL()` メソッドによって返されます。
+
+デベロッパー、`fullPath` 属性は *HTML ファイルシステムのルートに対する相対パス* のファイルへのパス。 したがって、上記のパスは今両方の `fullPath` と `FileEntry` オブジェクトで表される
+
+ /path/to/file
+
+
+デバイス絶対パスとアプリケーション動作以前 `Entry` オブジェクトの `fullPath` プロパティを使用してこれらのパスを取得した場合は、代わりに `entry.toURL()` を使用するコードを更新する必要があります。
+
+下位互換性、`resolveLocalFileSystemURL()` メソッドは、デバイス絶対パスを受け入れるし、は、`TEMPORARY` または `PERSISTENT` ファイル ・ システム内でそのファイルが存在する限り、それに対応する `Entry` オブジェクトを返します。
+
+これは特に以前デバイス絶対パスを使用してファイル転送のプラグインで問題となっている (そしてまだそれらを受け入れることができます)。 それがデバイス上のファイルで動作するプラグインを得る問題を解決する必要があります `entry.toURL()` で `entry.fullPath` を置き換えるので、ファイルシステムの Url で正常に動作にアップデートされました。
+
+V1.1.0 の `toURL()` の戻り値に変更されました (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) を参照) を絶対 'file://' で始まる URL を返します。 可能な限り。 確保するために、' cdvfile:'-`toInternalURL()` を今すぐ使用できます URL。 このメソッドは、フォームのファイルシステムの Url を返します今
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+これはファイルを一意に識別するために使用できます。
+
+## エラー コードと意味のリスト
+
+エラーがスローされると、次のコードのいずれかが使用されます。
+
+| コード | 定数 |
+| ---:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## (省略可能) プラグインを構成します。
+
+利用可能なファイルシステムのセットは構成されたプラットフォームをすることができます。IOS と Android の両方を認識します。 タグ `config.xml` をインストールするファイルシステムの名前します。既定では、すべてのファイル システムのルートが有効になります。
+
+
+
+
+
+### アンドロイド
+
+* `files`: アプリケーションの内部ファイルのストレージ ディレクトリ
+* `files-external`: アプリケーションの外部のファイルのストレージ ディレクトリ
+* `sdcard`:、グローバル外部ストレージ ディレクトリをファイル (これは SD カードのルートがインストールされている場合)。 これを使用するには、`android.permission.WRITE_EXTERNAL_STORAGE` 権限が必要です。
+* `cache`: アプリケーションの内部キャッシュ ディレクトリ
+* `cache-external`: 外部キャッシュのアプリケーションのディレクトリ
+* `root`: デバイス全体のファイルシステム
+
+アンドロイドを「ファイル」ファイルシステム内の"ドキュメント/"サブディレクトリを表す"ドキュメント"という名前の特殊なファイルシステムもサポートしています。
+
+### iOS
+
+* `library`: ライブラリのアプリケーションのディレクトリ
+* `documents`: ドキュメントのアプリケーションのディレクトリ
+* `cache`: キャッシュのアプリケーションのディレクトリ
+* `bundle`: アプリケーションバンドル;アプリ自体 (読み取りのみ) ディスク上の場所
+* `root`: デバイス全体のファイルシステム
+
+既定では、ライブラリとドキュメント ディレクトリを iCloud に同期できます。 2 つの追加のファイルシステム、`library-nosync` および `documents-nosync` を表す、特別な非同期ディレクトリ内を要求することもできます、`/Library` または `Documents/` ファイルシステム。
diff --git a/plugins/cordova-plugin-file/doc/ja/plugins.md b/plugins/cordova-plugin-file/doc/ja/plugins.md
new file mode 100644
index 0000000..c54aa78
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ja/plugins.md
@@ -0,0 +1,101 @@
+
+
+# プラグイン開発者のためのメモ
+
+これらのノートは主に Android と iOS 開発者インタ フェース ファイルのプラグインを使用してファイル システムでプラグインを書きたい人向け。
+
+## コルドバのファイル システムの Url での作業
+
+バージョン 1.0.0 では、以来、このプラグインを含む Url を使用する `cdvfile` JavaScript に raw デバイス ファイル システムのパスを公開するのではなく、橋の上のすべての通信方式します。
+
+JavaScript 側では、これはファイルと DirectoryEntry オブジェクトに HTML ファイル システムのルートを基準として、fullPath 属性があることを意味します。 あなたのプラグインの JavaScript API がファイルまたは DirectoryEntry オブジェクトを受け入れる場合を呼び出す必要があります `.toURL()` 橋を渡ってそれをネイティブ コードに渡す前にそのオブジェクトの。
+
+### Cdvfile に変換する://fileystem のパスに Url
+
+ファイルシステムへの書き込みする必要があるプラグインは、実際のファイルシステムの場所に受信したファイル システム URL に変換する必要があります。ネイティブ プラットフォームによって、これを行うための複数の方法があります。
+
+それを覚えていることが重要ですすべて `cdvfile://` の Url がデバイス上の実際のファイルをマッピング可能な。 いくつかの Url は、ファイルでは表されないまたはリモート リソースを参照することができますもデバイス上の資産を参照できます。 これらの可能性のためのプラグインは、戻るときにパスに Url を変換しようとして、彼らは意味のある結果を得るかどうか常にテスト必要があります。
+
+#### アンドロイド
+
+アンドロイド, に変換する最も簡単な方法で、 `cdvfile://` を使用するファイルシステムのパスに URL は `org.apache.cordova.CordovaResourceApi` 。 `CordovaResourceApi`扱うことができるいくつかの方法は、 `cdvfile://` の Url:
+
+ webView プラグイン クラス CordovaResourceApi resourceApi のメンバーである = webView.getResourceApi()。
+
+ デバイスでこのファイルを表す file:///URL を取得//ファイル Uri fileURL にマップできない場合、同じ URL は変更されません = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+また、ファイルのプラグインを直接使用することが可能です。
+
+ インポート org.apache.cordova.file.FileUtils;
+ インポート org.apache.cordova.file.FileSystem;
+ インポート java.net.MalformedURLException;
+
+ プラグイン マネージャーからファイルのプラグインを入手してコマンド filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ それを試みるためにパスを取得 URL を指定すると、{文字列パス = filePlugin.filesystemPathForURL(cdvfileURL);} キャッチ (MalformedURLException e) {/ファイルシステムの url が認識されませんでした/}
+
+
+パスから変換する、 `cdvfile://` URL:
+
+ インポート org.apache.cordova.file.LocalFilesystemURL;
+
+ デバイス ・ パスの LocalFilesystemURL オブジェクトを取得//cdvfile URL として表現できない場合は null。
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ URL オブジェクトの文字列 cdvfileURL の文字列表現を取得する = url.toString();
+
+
+あなたのプラグインは、ファイルを作成しをファイル オブジェクトを返す場合、ファイルのプラグインを使用します。
+
+ JavaScript を返すときに適した JSON 構造を返す//このファイルは cdvfile URL として表現できない場合は null。
+ JSONObject エントリ = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+IOS のコルドバは同じを使用しない `CordovaResourceApi` アンドロイドとしての概念。IOS では、Url とファイルシステムのパスの間を変換するファイル プラグインを使用する必要があります。
+
+ URL の文字列 CDVFilesystemURL * url から CDVFilesystem URL オブジェクトを取得 [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ ファイル NSString * パスにマップできない場合は nil または URL オブジェクトのパスを取得 [filePlugin filesystemPathForURL:url];
+
+
+ デバイス ・ パスの CDVFilesystem の URL オブジェクトを取得または//cdvfile URL として表現できない場合は nil です。
+ CDVFilesystemURL の url = [filePlugin fileSystemURLforLocalPath:path];
+ URL オブジェクト NSString * cdvfileURL の文字列表現を取得する = [url absoluteString];
+
+
+あなたのプラグインは、ファイルを作成しをファイル オブジェクトを返す場合、ファイルのプラグインを使用します。
+
+ デバイス ・ パスの CDVFilesystem の URL オブジェクトを取得または//cdvfile URL として表現できない場合は nil です。
+ CDVFilesystemURL の url = [filePlugin fileSystemURLforLocalPath:path];
+ JavaScript NSDictionary * エントリに戻る構造を得る = [filePlugin makeEntryForLocalURL:url]
+
+
+#### Java スクリプトの設定
+
+Java スクリプトの設定を取得するに、 `cdvfile://` ファイルまたは DirectoryEntry オブジェクトからの URL を呼び出して、 `.toURL()` それを。
+
+ var cdvfileURL = entry.toURL();
+
+
+プラグイン応答ハンドラーに返された FileEntry 構造体の実際のエントリ オブジェクトを変換する、ハンドラーのコード ファイルのプラグインをインポート、新しいオブジェクトを作成します。
+
+ 適切なエントリ オブジェクト var エントリを作成します。
+ 場合 (entryStruct.isDirectory) {エントリ = 新しい DirectoryEntry (entryStruct.name、entryStruct.fullPath、新しい FileSystem(entryStruct.filesystemName));} 他 {エントリ = 新しいファイル (entryStruct.name、entryStruct.fullPath、新しい FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/ko/README.md b/plugins/cordova-plugin-file/doc/ko/README.md
new file mode 100644
index 0000000..a3f3e94
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ko/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+이 플러그인은 장치에 있는 파일에 대 한 읽기/쓰기 액세스를 허용 하는 파일 API를 구현 합니다.
+
+이 플러그인을 포함 한 몇 가지 사양에 따라: HTML5 파일 API는
+
+(지금은 없어진) 디렉터리와 시스템 확장 최신: 플러그인 코드의 대부분은 때 이전 사양 작성 되었습니다 있지만 현재는:
+
+그것은 또한 FileWriter 사양 구현:
+
+사용을 참조 하십시오 HTML5 바위 ' 우수한 [파일 시스템 문서.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+다른 저장소 옵션에 대 한 개요, 코르도바의 [저장소 가이드](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html) 를 참조합니다.
+
+이 플러그인 글로벌 `cordova.file` 개체를 정의합니다.
+
+전역 범위에 있지만 그것은 불가능까지 `deviceready` 이벤트 후.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## 설치
+
+ cordova plugin add cordova-plugin-file
+
+
+## 지원 되는 플랫폼
+
+ * 아마존 화재 운영 체제
+ * 안 드 로이드
+ * 블랙베리 10
+ * Firefox 운영 체제
+ * iOS
+ * Windows Phone 7과 8 *
+ * 윈도우 8 *
+ * Windows*
+ * 브라우저
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## 파일을 저장할 위치를
+
+V1.2.0, 현재 중요 한 파일 시스템 디렉터리에 Url도 제공 됩니다. 각 URL 형태 *file:///path/to/spot/* 이며 `DirectoryEntry` `window.resolveLocalFileSystemURL()`를 사용 하 여 변환할 수 있습니다..
+
+ * `cordova.file.applicationDirectory`-읽기 전용 디렉터리는 응용 프로그램을 설치 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*)
+
+ * `cordova.file.applicationStorageDirectory`응용 프로그램의 샌드박스;의 루트 디렉터리 iOS에이 위치에는 읽기 전용 (특정 하위 디렉토리만 [같은 `/Documents` ]은 읽기 / 쓰기). 포함 된 모든 데이터는 응용 프로그램에 전용. ( *iOS*, *안 드 로이드*, *블랙베리 10*)
+
+ * `cordova.file.dataDirectory`-내부 메모리를 사용 하 여 응용 프로그램의 샌드박스 내에서 영구 및 개인 데이터 스토리지 (안 드 로이드, 외부 메모리를 사용 해야 하는 경우 사용 하 여 `.externalDataDirectory` ). IOS에이 디렉터리 iCloud와 동기화 되지 되 (를 사용 하 여 `.syncedDataDirectory` ). (*iOS*, *안 드 로이드*, *블랙베리 10*)
+
+ * `cordova.file.cacheDirectory`-디렉터리 캐시 데이터 파일 또는 모든 파일을 당신의 app를 다시 쉽게 만들 수 있습니다. 운영 체제 장치 저장소 부족 하면 이러한 파일을 삭제할 수 있습니다, 그리고 그럼에도 불구 하 고, 애플 리 케이 션 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-응용 프로그램 외부 저장 공간입니다. (*안 드 로이드*)
+
+ * `cordova.file.externalDataDirectory`-외부 저장소에 응용 프로그램 특정 데이터 파일을 넣어 어디. (*안 드 로이드*)
+
+ * `cordova.file.externalCacheDirectory`외부 저장소에 응용 프로그램 캐시입니다. (*안 드 로이드*)
+
+ * `cordova.file.externalRootDirectory`-외부 저장 (SD 카드) 루트입니다. (*안 드 로이드*, *블랙베리 10*)
+
+ * `cordova.file.tempDirectory`-운영 체제에서 지울 수 있습니다 임시 디렉터리 것입니다. 이 디렉터리;를 운영 체제에 의존 하지 마십시오 귀하의 응용 프로그램 항상 해당 하는 경우 파일을 제거 해야 합니다. (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-(ICloud)를 예를 들어 동기화 해야 하는 응용 프로그램 관련 파일을 보유 하 고 있습니다. (*iOS*)
+
+ * `cordova.file.documentsDirectory`-파일 애플 리 케이 션, 하지만 그 개인은 다른 응용 프로그램 (예: Office 파일)에 의미입니다. (*iOS*)
+
+ * `cordova.file.sharedDirectory`-모든 응용 프로그램 (*블랙베리 10* 에 전세계적으로 사용 가능한 파일)
+
+## 파일 시스템 레이아웃
+
+하지만 구현 세부 사항을 기술적으로 `cordova.file.*` 속성 실제 장치에 실제 경로에 매핑하는 방법을 아는 것이 매우 유용할 수 있습니다.
+
+### iOS 파일 시스템 레이아웃
+
+| 장치 경로 | `cordova.file.*` | `iosExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 동기화 | 개인 |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:--------:|:-------------:|:---:|:--:|
+| `/ var/모바일/응용 프로그램/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | 예 |
+| `appname.app/` | applicationDirectory | 번들 | r | N/A | N/A | N/A | 예 |
+| `www/` | - | - | r | N/A | N/A | N/A | 예 |
+| `Documents/` | documentsDirectory | 문서 | r/w | 예 | 없음 | 예 | 예 |
+| `NoCloud/` | - | 문서 nosync | r/w | 예 | 없음 | 없음 | 예 |
+| `Library` | - | 라이브러리 | r/w | 예 | 없음 | 그래? | 예 |
+| `NoCloud/` | dataDirectory | 라이브러리 nosync | r/w | 예 | 없음 | 없음 | 예 |
+| `Cloud/` | syncedDataDirectory | - | r/w | 예 | 없음 | 예 | 예 |
+| `Caches/` | cacheDirectory | 캐시 | r/w | 예 * | Yes**\* | 없음 | 예 |
+| `tmp/` | tempDirectory | - | r/w | No** | Yes**\* | 없음 | 예 |
+
+\ * 파일 응용 프로그램 다시 시작 및 업그레이드, 유지 하지만 때마다 OS 욕망이 디렉터리를 지울 수 있습니다. 앱 삭제 될 수 있습니다 모든 콘텐츠를 다시 만들 수 있어야 합니다.
+
+** 파일 응용 프로그램 다시 시작에서 지속 될 수 있습니다 하지만이 동작에 의존 하지 마십시오. 파일 여러 업데이트를 보장 하지 않습니다. 때 해당 앱이이 디렉터리에서 파일을 제거 해야, 이러한 파일을 제거할 때 (또는 경우에도) 운영 체제 보증 하지 않습니다으로.
+
+**\ * OS 그것이 필요를 느낀다 언제 든 지이 디렉터리의 내용을 취소 수 있습니다 하지만 이것에 의존 하지 마십시오. 이 디렉터리를 응용 프로그램에 대 한 적절 한 선택을 취소 해야 합니다.
+
+### 안 드 로이드 파일 시스템 레이아웃
+
+| 장치 경로 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 개인 |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:----:|:---:|:--------:|:--:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | 예 |
+| `/data/데이터/< app id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | 예 |
+| `cache` | cacheDirectory | 캐시 | r/w | 예 | 예\* | 예 |
+| `files` | dataDirectory | 파일 | r/w | 예 | 없음 | 예 |
+| `Documents` | | 문서 | r/w | 예 | 없음 | 예 |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | 예 | 없음 | 없음 |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | 예 | 없음 | 없음 |
+| `cache` | externalCacheDirectry | 외부 캐시 | r/w | 예 | 없음** | 없음 |
+| `files` | externalDataDirectory | 파일 외부 | r/w | 예 | 없음 | 없음 |
+
+\ * 운영 체제 정기적으로이 디렉터리 삭제 수 있지만이 동작에 의존 하지 마십시오. 이 응용 프로그램이 디렉터리의 내용을 취소 합니다. 사용자 수동으로 캐시 제거 해야,이 디렉터리의 내용은 제거 됩니다.
+
+** 운영 체제 자동으로;이 디렉터리를 삭제 하지 않습니다 내용을 직접 관리에 대 한 책임이 있습니다. 사용자 수동으로 캐시 제거 합니다, 디렉터리의 내용은 제거 됩니다.
+
+**참고**: 외부 저장소를 탑재할 수 없는 경우 `cordova.file.external*` 속성은 `null`.
+
+### 블랙베리 10 파일 시스템 레이아웃
+
+| 장치 경로 | `cordova.file.*` | r/w? | 영구? | OS 지웁니다 | 개인 |
+|:----------------------------------------------------------- |:--------------------------- |:----:|:---:|:-------:|:--:|
+| `file:///accounts/1000/appdata/ < app id > /` | applicationStorageDirectory | r | N/A | N/A | 예 |
+| `app/native` | applicationDirectory | r | N/A | N/A | 예 |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 없음 | 예 | 예 |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 예 | 없음 | 예 |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 예 | 없음 | 없음 |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | 예 | 없음 | 없음 |
+
+*참고*: 모든 경로 /accounts/1000-enterprise를 기준으로 응용 프로그램 경계를 작동 하도록 배포 될 때.
+
+## 안 드 로이드 단점
+
+### 안 드 로이드 영구 저장 위치
+
+안 드 로이드 장치에 영구 파일을 저장할 여러 유효한 위치가 있다. 다양 한 가능성의 광범위 한 토론에 대 한 [이 페이지](http://developer.android.com/guide/topics/data/data-storage.html)를 참조 하십시오.
+
+플러그인의 이전 버전을 시작할 때, 장치는 SD 카드 (또는 해당 스토리지 파티션) 탑재 했다 주장 하는 여부에 따라 임시 및 영구 파일의 위치를 선택 합니다. SD 카드 마운트, 또는 큰 내부 스토리지 파티션에 사용할 수 있었습니다 (같은 넥서스 장치에) 그 후에 영구 파일 공간의 루트에 저장 됩니다. 이 모든 코르 도우 바 애플 리 케이 션 카드에 모두 사용할 수 있는 파일을 볼 수 있는 의미 합니다.
+
+SD 카드는 사용할 수 있는 경우 이전 버전에서 데이터 저장 `/data/data/`는 서로 다른 애플 리 케이 션을 분리 하지만 여전히 원인 데이터를 사용자 간에 공유할 수 있습니다.
+
+그것은 지금 내부 파일 저장 위치 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 이전 논리를 사용 하 여 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가:
+
+
+
+
+
+
+이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다.
+
+이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. "내부"의 위치 전환 그들의 응용 프로그램을 업그레이드 기존 사용자의 그들의 장치에 따라 그들의 이전에 저장 된 파일에 액세스할 수 수 있다는 뜻입니다.
+
+경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Internal` 설정은 일반적으로 권장 됩니다.
+
+### /Android_asset에 대 한 느린 재귀 작업
+
+자산 디렉터리를 나열 하는 것은 안 드 로이드에 정말 느리다입니다. 속도 높일 수 있습니다 하지만, 안 드 로이드 프로젝트의 루트에 `src/android/build-extras.gradle` 를 추가 하 여 최대 (cordova-android@4.0.0 필요 이상).
+
+## iOS 단점
+
+ * `cordova.file.applicationStorageDirectory`읽기 전용; 루트 디렉터리 내에서 파일을 저장 하려고에 실패 합니다. 다른 중 하나를 사용 하 여 `cordova.file.*` iOS에 대해 정의 된 속성 (만 `applicationDirectory` 와 `applicationStorageDirectory` 는 읽기 전용).
+ * `FileReader.readAsText(blob, encoding)`
+ * `encoding`매개 변수는 지원 되지 않습니다, 및 효과에 항상 u t F-8 인코딩을 합니다.
+
+### iOS 영구 저장소 위치
+
+IOS 디바이스에 영구 파일을 저장할 두 개의 유효한 위치가 있다: 문서 디렉터리 및 라이브러리 디렉터리. 플러그인의 이전 버전은 오직 문서 디렉토리에 영구 파일을 저장. 이 부작용 보다는 아니었다 수시로 특히 많은 작은 파일을 처리 하는 응용 프로그램에 대 한 의도, iTunes에 표시 모든 응용 프로그램 파일을 만드는 디렉터리의 용도 내보내기에 대 한 완전 한 문서를 생산 했다.
+
+그것은 지금 문서 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 라이브러리 디렉토리에 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가:
+
+
+
+
+
+
+이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다.
+
+이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. `Library`에 위치를 스위칭 기존 사용자에 게 응용 프로그램을 업그레이 드의 그들의 이전에 저장 된 파일에 액세스할 수 것을 의미할 것입니다.
+
+경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Library` 설정은 일반적으로 권장 됩니다.
+
+## 파이어 폭스 OS 단점
+
+파일 시스템 API Firefox 운영 체제에서 기본적으로 지원 하지 및 indexedDB 위에 심으로 구현 됩니다.
+
+ * 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다.
+ * 디렉터리에 대 한 메타 데이터를 지원 하지 않습니다.
+ * 메서드 `copyTo` 및 `moveTo` 디렉터리를 지원 하지 않습니다
+
+다음 데이터 경로 지원 됩니다: * `applicationDirectory`-`xhr`를 사용 하 여 로컬 파일을 응용 프로그램 패키지를 가져옵니다. * `dataDirectory`-영구 응용 프로그램 특정 데이터 파일에 대 한. * `cacheDirectory`-응용 프로그램 다시 시작 해야 하는 캐시 된 파일 (애플 리 케이 션은 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야).
+
+## 브라우저 만지면
+
+### 일반적인 단점 및 설명
+
+ * 각 브라우저는 샌드박스 자체 파일 시스템을 사용합니다. IE와 파이어 폭스 기반으로 IndexedDB를 사용합니다. 모든 브라우저는 경로에서 디렉터리 구분 기호로 슬래시를 사용합니다.
+ * 디렉터리 항목을 연속적으로 만들 수 있다. 예를 들어 전화 `fs.root.getDirectory ('dir1/dir2 ', {create:true}, successCallback, errorCallback)` d i r 1 존재 하지 않은 경우 실패 합니다.
+ * 플러그인 응용 프로그램 처음 시작할 영구 저장소를 사용 하 여 사용자 권한을 요청 합니다.
+ * 플러그인 지원 `cdvfile://localhost` (로컬 리소스)만. 즉, 외부 리소스는 `cdvfile`를 통해 지원 되지 않습니다..
+ * 플러그인 ["파일 시스템 API 8.3 명명 제한"을](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions) 수행 하지 않습니다..
+ * Blob 및 파일 ' `close` 함수는 지원 되지 않습니다.
+ * `FileSaver` 및 `BlobBuilder`는이 플러그 접속식에 의해 지원 되지 않습니다 그리고 명세서를 필요가 없습니다.
+ * 플러그인 `requestAllFileSystems`를 지원 하지 않습니다. 이 함수는 또한 사양에 빠진.
+ * 사용 하는 경우 디렉터리에서 항목 제거 되지 것입니다 `create: true` 기존 디렉터리에 대 한 플래그.
+ * 생성자를 통해 생성 된 파일은 지원 되지 않습니다. Entry.file 메서드를 대신 사용 해야 합니다.
+ * 각 브라우저 blob URL 참조에 대 한 그것의 자신의 형태를 사용합니다.
+ * `readAsDataURL` 기능을 지원 하지만 크롬에서 mediatype 항목 이름 확장명에 따라 달라 집니다, 그리고 mediatype IE에는 항상 빈 (`텍스트 일반` 사양에 따라 동일), 파이어 폭스에서 mediatype은 항상 `응용 프로그램/8 진수 스트림`. 예를 들어, 콘텐츠는 `abcdefg` 다음 파이어 폭스 반환 `데이터: 응용 프로그램 / 8 진수 스트림; base64, YWJjZGVmZw = =`, 즉 반환 `데이터:; base64, YWJjZGVmZw = =`, 반환 크롬 `데이터: < 항목 이름의 확장에 따라 mediatype >; base64, YWJjZGVmZw = =`.
+ * `toInternalURL` 양식 `file:///persistent/path/to/entry` (파이어 폭스, 인터넷 익스플로러)에서 경로 반환합니다. 크롬 양식 `cdvfile://localhost/persistent/file`에 경로 반환합니다..
+
+### 크롬 특수
+
+ * 크롬 파일 시스템 장치 준비 이벤트 후 즉시 준비 되지 않습니다. 문제를 해결 하려면 `filePluginIsReady` 이벤트를 구독할 수 있습니다. 예를 들어:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+`Window.isFilePluginReadyRaised` 함수를 사용 하 여 이벤트가 이미 발생 여부를 확인할 수 있습니다. -window.requestFileSystem 임시 및 영구 파일 시스템 할당량 크롬에 제한 되지 않습니다. -크롬에서 영구 저장소를 증가 하려면 `window.initPersistentFileSystem` 메서드를 호출 해야 합니다. 영구 저장소 할당량은 기본적으로 5 메가바이트입니다. -크롬 필요 `-허용-파일-액세스-에서-파일` `file:///` 프로토콜을 통해 지원 API 인수를 실행 합니다. -플래그를 사용 하면 `파일` 개체 하지 변경할 수 `{create:true}` 때 기존 `항목`. -행사 `cancelable` 속성이로 설정 된 크롬에서. 이 [사양](http://dev.w3.org/2009/dap/file-system/file-writer.html) 대조적 이다. -크롬에서 `toURL` 함수 반환 합니다 `파일 시스템:`-응용 프로그램 호스트에 따라 경로 앞에. 예를 들어, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` 함수 결과 디렉터리 항목의 경우에 후행 슬래시를 포함 하지 않습니다. 크롬 하지만 제대로 붙여 슬래시 url이 포함 된 디렉터리 해결합니다. -`resolveLocalFileSystemURL` 메서드 인바운드 `url`을 `파일 시스템` 접두사가 필요 합니다. 예를 들어, `url` 매개 변수 `resolveLocalFileSystemURL`에 대 한 안 드 로이드에서 양식 `file:///persistent/somefile.txt` 반대로 양식 `filesystem:file:///persistent/somefile.txt`에 있어야 합니다. -사용 되지 않는 `toNativeURL` 함수는 지원 되지 않습니다 및 stub에는 없습니다. -`setMetadata` 함수는 규격에 명시 되지 않은 및 지원 되지 않습니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 SYNTAX_ERR(code: 8) 비 existant 파일 시스템의 요청에. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 PATH_EXISTS_ERR(code: 12) 독점적으로 파일 또는 디렉터리를 만들 려,는 이미 존재 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NO_MODIFICATION_ALLOWED_ERR(code: 6) 루트 파일 시스템에 removeRecursively을 호출 하려고 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NOT_FOUND_ERR(code: 1) moveTo 디렉터리 존재 하지 않는 것을 시도에.
+
+### IndexedDB 기반 구현이 특수 (파이어 폭스와 IE)
+
+ * `.` `.`는 지원 되지 않습니다.
+ * IE `file:///`를 지원 하지 않습니다-모드; 호스트 모드 지원된 (http://localhost:xxxx)입니다.
+ * 파이어 폭스 파일 시스템 크기 제한 이지만 각 50MB 확장 사용자 권한을 요청 합니다. IE10 최대 10 mb 결합 AppCache 및 IndexedDB 묻는 사이트 당 250 mb의 최대 최대 증가 될 수 있도록 하려는 경우 해당 수준에 충돌 한 번 메시지를 표시 하지 않고 파일 시스템의 구현에 사용을 허용 한다. 그래서 `size` 매개 변수 `requestFileSystem` 함수에 대 한 파이어 폭스와 IE에서 파일 시스템 영향을 주지 않습니다.
+ * `readAsBinaryString` 함수 사양에 명시 되지 않은 IE에서 지원 되지 않으며 stub에는 없습니다.
+ * `file.type`은 항상 null입니다.
+ * 하지 항목 삭제 된 DirectoryEntry 인스턴스의 콜백 결과 사용 하 여 만들어야 합니다. 그렇지 않으면, '교수형 항목'을 얻을 것 이다.
+ * 그냥 작성 된 파일을 읽을 수 있는이 파일의 새 인스턴스를 얻으려면 해야 합니다.
+ * `setMetadata` 함수는 사양에 명시 되지 않은 지원 `modificationTime` 필드 변경에만 해당 합니다.
+ * `copyTo` 및 `moveTo` 함수는 디렉터리를 지원 하지 않습니다.
+ * 디렉터리 메타 데이터는 지원 되지 않습니다.
+ * 둘 다 Entry.remove와 directoryEntry.removeRecursively 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다-디렉터리 제거 되는 대신 내용을 함께 청소.
+ * `abort` 및 `truncate` 함수 지원 되지 않습니다.
+ * 진행 이벤트가 발생 하지 합니다. 예를 들어,이 처리기 하지 실행 됩니다.
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## 업그레이드 노트
+
+이 플러그인의 v1.0.0에 게시 된 사양에 맞춰 더 많은 것 `FileEntry` 및 `DirectoryEntry` 구조 변경 되었습니다.
+
+플러그인의 이전 (pre-1.0.0) 버전 장치 절대 파일 위치 `Entry` 개체의 `fullPath` 속성에 저장 됩니다. 이러한 경로 일반적으로 같습니다.
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+이러한 경로 `항목` 개체의 `toURL()` 메서드에서 반환 했다.
+
+V1.0.0, `fullPath` 속성은 *HTML 파일 시스템의 루트에 상대적인* 파일의 경로를. 그래서, 위의 경로 지금 둘 다의 `fullPath`와 `FileEntry` 개체에 의해 표현 될 것 이다
+
+ /path/to/file
+
+
+응용 프로그램 작동 장치 절대 경로, 이전 `항목` 개체의 `fullPath` 속성을 통해 그 경로 검색 하는 경우에, 당신은 대신 `entry.toURL()`를 사용 하 여 코드를 업데이트 해야 합니다.
+
+대 한 뒤 호환성, `resolveLocalFileSystemURL()` 메서드는 장치-절대-경로 수락 하 고 그 파일 중 `TEMPORARY` 또는 `PERSISTENT` 파일 시스템 내에서 존재 하는 경우, 해당 `Entry` 개체를 반환 합니다.
+
+이 특히 이전 장치 절대 경로 사용 하는 파일 전송 플러그인에 문제가 있다 (그리고 아직도 그들을 받아들일 수.) 그것은 `entry.toURL()`와 `entry.fullPath`를 대체 확인 장치에 파일을 사용 하는 플러그인을 지 고 그래서 파일 시스템 Url와 함께 제대로 작동 하려면 업데이트 되었습니다.
+
+V1.1.0에 `toURL()`의 반환 값 (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) 참조)로 바뀌었다 'file://' 절대 URL을 반환. 가능 하다 면. 보장 하는 ' cdvfile:'-URL `toInternalURL()`를 지금 사용할 수 있습니다. 이 메서드 이제 양식의 파일 Url을 반환 합니다.
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+어떤 파일을 고유 하 게 식별 하려면 사용할 수 있습니다.
+
+## 오류 코드 및 의미의 목록
+
+오류가 throw 됩니다 때 다음 코드 중 하나가 사용 됩니다.
+
+| 코드 | 상수 |
+| --:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## (선택 사항) 플러그인 구성
+
+사용 가능한 파일 시스템의 집합 플랫폼 당 구성된 될 수 있습니다. IOS와 안 드 로이드를 인식 한 `config.xml` 설치 될 파일 시스템 이름에 태그. 기본적으로 모든 파일 시스템 루트 사용할 수 있습니다.
+
+
+
+
+
+### 안 드 로이드
+
+ * `files`: 응용 프로그램의 내부 파일 저장 디렉토리
+ * `files-external`: 응용 프로그램의 외부 파일 저장 디렉토리
+ * `sdcard`: 글로벌 외부 파일 저장 디렉토리 (이것은 SD 카드의 루트 설치 된 경우). 이것을 사용 하려면 `android.permission.WRITE_EXTERNAL_STORAGE` 권한이 있어야 합니다.
+ * `cache`: 응용 프로그램의 내부 캐시 디렉터리
+ * `cache-external`: 응용 프로그램의 외부 캐시 디렉터리
+ * `root`: 전체 장치 파일 시스템
+
+안 드 로이드는 또한 "파일" 파일 시스템 내에서 "/ 문서 /" 하위 디렉토리를 나타내는 "문서" 라는 특별 한 파일을 지원 합니다.
+
+### iOS
+
+ * `library`: 응용 프로그램의 라이브러리 디렉터리
+ * `documents`: 응용 프로그램의 문서 디렉토리
+ * `cache`: 응용 프로그램의 캐시 디렉터리
+ * `bundle`: 응용 프로그램의 번들; (읽기 전용) 디스크에 응용 프로그램 자체의 위치
+ * `root`: 전체 장치 파일 시스템
+
+기본적으로 라이브러리 및 문서 디렉토리 iCloud에 동기화 할 수 있습니다. 또한 2 개의 추가적인 파일 시스템, `library-nosync` 및 `documents-nosync`, 내 특별 한 동기화 되지 않은 디렉터리를 대표 하는 요청할 수 있습니다는 `/Library` 또는 `/Documents` 파일 시스템.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/ko/index.md b/plugins/cordova-plugin-file/doc/ko/index.md
new file mode 100644
index 0000000..08340d8
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ko/index.md
@@ -0,0 +1,338 @@
+
+
+# cordova-plugin-file
+
+이 플러그인은 장치에 있는 파일에 대 한 읽기/쓰기 액세스를 허용 하는 파일 API를 구현 합니다.
+
+이 플러그인을 포함 한 몇 가지 사양에 따라: HTML5 파일 API는
+
+(지금은 없어진) 디렉터리와 시스템 확장 최신: 플러그인 코드의 대부분은 때 이전 사양 작성 되었습니다 있지만 현재는:
+
+그것은 또한 FileWriter 사양 구현:
+
+사용을 참조 하십시오 HTML5 바위 ' 우수한 [파일 시스템 문서.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+다른 저장소 옵션에 대 한 개요, 코르도바의 [저장소 가이드][2] 를 참조합니다.
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+이 플러그인 글로벌 `cordova.file` 개체를 정의합니다.
+
+전역 범위에 있지만 그것은 불가능까지 `deviceready` 이벤트 후.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## 설치
+
+ cordova plugin add cordova-plugin-file
+
+
+## 지원 되는 플랫폼
+
+* 아마존 화재 운영 체제
+* 안 드 로이드
+* 블랙베리 10
+* Firefox 운영 체제
+* iOS
+* Windows Phone 7과 8 *
+* 윈도우 8 *
+* 브라우저
+
+* *`FileReader.readAsArrayBuffer`도 `FileWriter.write(blob)`이 플랫폼을 지원 하지 않습니다.*
+
+## 파일을 저장할 위치를
+
+V1.2.0, 현재 중요 한 파일 시스템 디렉터리에 Url도 제공 됩니다. 각 URL 형태 *file:///path/to/spot/* 이며 `DirectoryEntry` `window.resolveLocalFileSystemURL()`를 사용 하 여 변환할 수 있습니다..
+
+* `cordova.file.applicationDirectory`-읽기 전용 디렉터리는 응용 프로그램을 설치 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*)
+
+* `cordova.file.applicationStorageDirectory`응용 프로그램의 샌드박스;의 루트 디렉터리 iOS에이 위치에는 읽기 전용 (특정 하위 디렉토리만 [같은 `/Documents` ]은 읽기 / 쓰기). 포함 된 모든 데이터는 응용 프로그램에 전용. ( *iOS*, *안 드 로이드*, *블랙베리 10*)
+
+* `cordova.file.dataDirectory`-내부 메모리를 사용 하 여 응용 프로그램의 샌드박스 내에서 영구 및 개인 데이터 스토리지 (안 드 로이드, 외부 메모리를 사용 해야 하는 경우 사용 하 여 `.externalDataDirectory` ). IOS에이 디렉터리 iCloud와 동기화 되지 되 (를 사용 하 여 `.syncedDataDirectory` ). (*iOS*, *안 드 로이드*, *블랙베리 10*)
+
+* `cordova.file.cacheDirectory`-디렉터리 캐시 데이터 파일 또는 모든 파일을 당신의 app를 다시 쉽게 만들 수 있습니다. 운영 체제 장치 저장소 부족 하면 이러한 파일을 삭제할 수 있습니다, 그리고 그럼에도 불구 하 고, 애플 리 케이 션 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야 합니다. (*iOS*, *안 드 로이드*, *블랙베리 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-응용 프로그램 외부 저장 공간입니다. (*안 드 로이드*)
+
+* `cordova.file.externalDataDirectory`-외부 저장소에 응용 프로그램 특정 데이터 파일을 넣어 어디. (*안 드 로이드*)
+
+* `cordova.file.externalCacheDirectory`외부 저장소에 응용 프로그램 캐시입니다. (*안 드 로이드*)
+
+* `cordova.file.externalRootDirectory`-외부 저장 (SD 카드) 루트입니다. (*안 드 로이드*, *블랙베리 10*)
+
+* `cordova.file.tempDirectory`-운영 체제에서 지울 수 있습니다 임시 디렉터리 것입니다. 이 디렉터리;를 운영 체제에 의존 하지 마십시오 귀하의 응용 프로그램 항상 해당 하는 경우 파일을 제거 해야 합니다. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-(ICloud)를 예를 들어 동기화 해야 하는 응용 프로그램 관련 파일을 보유 하 고 있습니다. (*iOS*)
+
+* `cordova.file.documentsDirectory`-파일 애플 리 케이 션, 하지만 그 개인은 다른 응용 프로그램 (예: Office 파일)에 의미입니다. (*iOS*)
+
+* `cordova.file.sharedDirectory`-모든 응용 프로그램 (*블랙베리 10* 에 전세계적으로 사용 가능한 파일)
+
+## 파일 시스템 레이아웃
+
+하지만 구현 세부 사항을 기술적으로 `cordova.file.*` 속성 실제 장치에 실제 경로에 매핑하는 방법을 아는 것이 매우 유용할 수 있습니다.
+
+### iOS 파일 시스템 레이아웃
+
+| 장치 경로 | `cordova.file.*` | `iosExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 동기화 | 개인 |
+|:------------------------------------ |:--------------------------- |:--------------------- |:----:|:------:|:---------:|:---:|:--:|
+| `/ var/모바일/응용 프로그램/< UUID > /` | applicationStorageDirectory | - | r | N/A | N/A | N/A | 예 |
+| `appname.app/` | applicationDirectory | 번들 | r | N/A | N/A | N/A | 예 |
+| `www/` | - | - | r | N/A | N/A | N/A | 예 |
+| `Documents/` | documentsDirectory | 문서 | r/w | 예 | 없음 | 예 | 예 |
+| `NoCloud/` | - | 문서 nosync | r/w | 예 | 없음 | 없음 | 예 |
+| `Library` | - | 라이브러리 | r/w | 예 | 없음 | 그래? | 예 |
+| `NoCloud/` | dataDirectory | 라이브러리 nosync | r/w | 예 | 없음 | 없음 | 예 |
+| `Cloud/` | syncedDataDirectory | - | r/w | 예 | 없음 | 예 | 예 |
+| `Caches/` | cacheDirectory | 캐시 | r/w | 예 * | 예 * * *| | 없음 | 예 |
+| `tmp/` | tempDirectory | - | r/w | 아니 * * | 예 * * *| | 없음 | 예 |
+
+* 파일 응용 프로그램 다시 시작 및 업그레이드, 유지 하지만 OS 욕망 언제 든 지이 디렉터리를 지울 수 있습니다. 앱 삭제 될 수 있습니다 모든 콘텐츠를 다시 만들 수 있어야 합니다.
+
+* * 파일 응용 프로그램 다시 시작에서 지속 될 수 있습니다 하지만이 동작에 의존 하지 마십시오. 파일 여러 업데이트를 보장 하지 않습니다. 때 해당 앱이이 디렉터리에서 파일을 제거 해야, 이러한 파일을 제거할 때 (또는 경우에도) 운영 체제 보증 하지 않습니다으로.
+
+* * *| OS 그것이 필요를 느낀다 언제 든 지이 디렉터리의 내용을 취소 될 수 있습니다 하지만 이것에 의존 하지 마십시오. 이 디렉터리를 응용 프로그램에 대 한 적절 한 선택을 취소 해야 합니다.
+
+### 안 드 로이드 파일 시스템 레이아웃
+
+| 장치 경로 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | 영구? | OS 지웁니다 | 개인 |
+|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:---:|:-------:|:--:|
+| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | 예 |
+| `/data/데이터/< app id > /` | applicationStorageDirectory | - | r/w | N/A | N/A | 예 |
+| `cache` | cacheDirectory | 캐시 | r/w | 예 | 예 * | 예 |
+| `files` | dataDirectory | 파일 | r/w | 예 | 없음 | 예 |
+| `Documents` | | 문서 | r/w | 예 | 없음 | 예 |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | 예 | 없음 | 없음 |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | 예 | 없음 | 없음 |
+| `cache` | externalCacheDirectry | 외부 캐시 | r/w | 예 | 아니 * * | 없음 |
+| `files` | externalDataDirectory | 파일 외부 | r/w | 예 | 없음 | 없음 |
+
+* OS 수 있습니다 정기적으로이 디렉터리에 있지만이 동작에 의존 하지 마십시오. 이 응용 프로그램이 디렉터리의 내용을 취소 합니다. 사용자 수동으로 캐시 제거 해야,이 디렉터리의 내용은 제거 됩니다.
+
+* * OS 지워지지 않습니다이 디렉터리 자동으로; 콘텐츠를 관리 하기 위한 책임이 있습니다. 사용자 수동으로 캐시 제거 합니다, 디렉터리의 내용은 제거 됩니다.
+
+**참고**: 외부 저장소를 탑재할 수 없는 경우 `cordova.file.external*` 속성은 `null`.
+
+### 블랙베리 10 파일 시스템 레이아웃
+
+| 장치 경로 | `cordova.file.*` | r/w? | 영구? | OS 지웁니다 | 개인 |
+|:--------------------------------------------------- |:--------------------------- |:----:|:---:|:-------:|:--:|
+| `file:///accounts/1000/appdata/ < app id > /` | applicationStorageDirectory | r | N/A | N/A | 예 |
+| `app/native` | applicationDirectory | r | N/A | N/A | 예 |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 없음 | 예 | 예 |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 예 | 없음 | 예 |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 예 | 없음 | 없음 |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | 예 | 없음 | 없음 |
+
+*참고*: 모든 경로 /accounts/1000-enterprise를 기준으로 응용 프로그램 경계를 작동 하도록 배포 될 때.
+
+## 안 드 로이드 단점
+
+### 안 드 로이드 영구 저장 위치
+
+안 드 로이드 장치에 영구 파일을 저장할 여러 유효한 위치가 있다. 다양 한 가능성의 광범위 한 토론에 대 한 [이 페이지][3]를 참조 하십시오.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+플러그인의 이전 버전을 시작할 때, 장치는 SD 카드 (또는 해당 스토리지 파티션) 탑재 했다 주장 하는 여부에 따라 임시 및 영구 파일의 위치를 선택 합니다. SD 카드 마운트, 또는 큰 내부 스토리지 파티션에 사용할 수 있었습니다 (같은 넥서스 장치에) 그 후에 영구 파일 공간의 루트에 저장 됩니다. 이 모든 코르 도우 바 애플 리 케이 션 카드에 모두 사용할 수 있는 파일을 볼 수 있는 의미 합니다.
+
+SD 카드는 사용할 수 있는 경우 이전 버전에서 데이터 저장 `/data/data/`는 서로 다른 애플 리 케이 션을 분리 하지만 여전히 원인 데이터를 사용자 간에 공유할 수 있습니다.
+
+그것은 지금 내부 파일 저장 위치 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 이전 논리를 사용 하 여 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가:
+
+
+
+
+
+
+이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다.
+
+이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. "내부"의 위치 전환 그들의 응용 프로그램을 업그레이드 기존 사용자의 그들의 장치에 따라 그들의 이전에 저장 된 파일에 액세스할 수 수 있다는 뜻입니다.
+
+경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Internal` 설정은 일반적으로 권장 됩니다.
+
+## iOS 단점
+
+* `cordova.file.applicationStorageDirectory`읽기 전용; 루트 디렉터리 내에서 파일을 저장 하려고에 실패 합니다. 다른 중 하나를 사용 하 여 `cordova.file.*` iOS에 대해 정의 된 속성 (만 `applicationDirectory` 와 `applicationStorageDirectory` 는 읽기 전용).
+* `FileReader.readAsText(blob, encoding)`
+ * `encoding`매개 변수는 지원 되지 않습니다, 및 효과에 항상 u t F-8 인코딩을 합니다.
+
+### iOS 영구 저장소 위치
+
+IOS 디바이스에 영구 파일을 저장할 두 개의 유효한 위치가 있다: 문서 디렉터리 및 라이브러리 디렉터리. 플러그인의 이전 버전은 오직 문서 디렉토리에 영구 파일을 저장. 이 부작용 보다는 아니었다 수시로 특히 많은 작은 파일을 처리 하는 응용 프로그램에 대 한 의도, iTunes에 표시 모든 응용 프로그램 파일을 만드는 디렉터리의 용도 내보내기에 대 한 완전 한 문서를 생산 했다.
+
+그것은 지금 문서 또는 응용 프로그램의 `config.xml` 파일에 기본 설정으로 라이브러리 디렉토리에 파일을 저장할 것인지를 선택할 수 있습니다. 이렇게 하려면 `config.xml`에이 두 줄 중 하나를 추가:
+
+
+
+
+
+
+이 줄이 없으면 파일 플러그인은 기본적으로 `Compatibility`을 사용 합니다. 기본 태그,이 이러한 값 중 하나가 아닌 경우에 응용 프로그램이 시작 되지 않습니다.
+
+이전 (사전 1.0)을 사용 하는 경우 응용 프로그램 사용자에 게 발송 되었다 이전,이 플러그인의 버전 영구 파일 시스템에 저장 된 파일은 그리고 `Compatibility` 환경 설정을 설정 해야 합니다. `Library`에 위치를 스위칭 기존 사용자에 게 응용 프로그램을 업그레이 드의 그들의 이전에 저장 된 파일에 액세스할 수 것을 의미할 것입니다.
+
+경우 응용 프로그램은 새로운, 또는 이전 영구 파일 시스템에 파일을 저장, `Library` 설정은 일반적으로 권장 됩니다.
+
+## 파이어 폭스 OS 단점
+
+파일 시스템 API Firefox 운영 체제에서 기본적으로 지원 하지 및 indexedDB 위에 심으로 구현 됩니다.
+
+* 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다.
+* 디렉터리에 대 한 메타 데이터를 지원 하지 않습니다.
+* 메서드 `copyTo` 및 `moveTo` 디렉터리를 지원 하지 않습니다
+
+다음 데이터 경로 지원 됩니다: * `applicationDirectory`-`xhr`를 사용 하 여 로컬 파일을 응용 프로그램 패키지를 가져옵니다. * `dataDirectory`-영구 응용 프로그램 특정 데이터 파일에 대 한. * `cacheDirectory`-응용 프로그램 다시 시작 해야 하는 캐시 된 파일 (애플 리 케이 션은 여기에 파일을 삭제 하려면 운영 체제에 의존 하지 말아야).
+
+## 브라우저 만지면
+
+### 일반적인 단점 및 설명
+
+* 각 브라우저는 샌드박스 자체 파일 시스템을 사용합니다. IE와 파이어 폭스 기반으로 IndexedDB를 사용합니다. 모든 브라우저는 경로에서 디렉터리 구분 기호로 슬래시를 사용합니다.
+* 디렉터리 항목을 연속적으로 만들 수 있다. 예를 들어 전화 `fs.root.getDirectory ('dir1/dir2 ', {create:true}, successCallback, errorCallback)` d i r 1 존재 하지 않은 경우 실패 합니다.
+* 플러그인 응용 프로그램 처음 시작할 영구 저장소를 사용 하 여 사용자 권한을 요청 합니다.
+* 플러그인 지원 `cdvfile://localhost` (로컬 리소스)만. 즉, 외부 리소스는 `cdvfile`를 통해 지원 되지 않습니다..
+* 플러그인 ["파일 시스템 API 8.3 명명 제한"을][4] 수행 하지 않습니다..
+* Blob 및 파일 ' `close` 함수는 지원 되지 않습니다.
+* `FileSaver` 및 `BlobBuilder`는이 플러그 접속식에 의해 지원 되지 않습니다 그리고 명세서를 필요가 없습니다.
+* 플러그인 `requestAllFileSystems`를 지원 하지 않습니다. 이 함수는 또한 사양에 빠진.
+* 사용 하는 경우 디렉터리에서 항목 제거 되지 것입니다 `create: true` 기존 디렉터리에 대 한 플래그.
+* 생성자를 통해 생성 된 파일은 지원 되지 않습니다. Entry.file 메서드를 대신 사용 해야 합니다.
+* 각 브라우저 blob URL 참조에 대 한 그것의 자신의 형태를 사용합니다.
+* `readAsDataURL` 기능을 지원 하지만 크롬에서 mediatype 항목 이름 확장명에 따라 달라 집니다, 그리고 mediatype IE에는 항상 빈 (`텍스트 일반` 사양에 따라 동일), 파이어 폭스에서 mediatype은 항상 `응용 프로그램/8 진수 스트림`. 예를 들어, 콘텐츠는 `abcdefg` 다음 파이어 폭스 반환 `데이터: 응용 프로그램 / 8 진수 스트림; base64, YWJjZGVmZw = =`, 즉 반환 `데이터:; base64, YWJjZGVmZw = =`, 반환 크롬 `데이터: < 항목 이름의 확장에 따라 mediatype >; base64, YWJjZGVmZw = =`.
+* `toInternalURL` 양식 `file:///persistent/path/to/entry` (파이어 폭스, 인터넷 익스플로러)에서 경로 반환합니다. 크롬 양식 `cdvfile://localhost/persistent/file`에 경로 반환합니다..
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### 크롬 특수
+
+* 크롬 파일 시스템 장치 준비 이벤트 후 즉시 준비 되지 않습니다. 문제를 해결 하려면 `filePluginIsReady` 이벤트를 구독할 수 있습니다. 예를 들어:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+`Window.isFilePluginReadyRaised` 함수를 사용 하 여 이벤트가 이미 발생 여부를 확인할 수 있습니다. -window.requestFileSystem 임시 및 영구 파일 시스템 할당량 크롬에 제한 되지 않습니다. -크롬에서 영구 저장소를 증가 하려면 `window.initPersistentFileSystem` 메서드를 호출 해야 합니다. 영구 저장소 할당량은 기본적으로 5 메가바이트입니다. -크롬 필요 `-허용-파일-액세스-에서-파일` `file:///` 프로토콜을 통해 지원 API 인수를 실행 합니다. -플래그를 사용 하면 `파일` 개체 하지 변경할 수 `{create:true}` 때 기존 `항목`. -행사 `cancelable` 속성이로 설정 된 크롬에서. 이 [사양][5] 대조적 이다. -크롬에서 `toURL` 함수 반환 합니다 `파일 시스템:`-응용 프로그램 호스트에 따라 경로 앞에. 예를 들어, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -`toURL` 함수 결과 디렉터리 항목의 경우에 후행 슬래시를 포함 하지 않습니다. 크롬 하지만 제대로 붙여 슬래시 url이 포함 된 디렉터리 해결합니다. -`resolveLocalFileSystemURL` 메서드 인바운드 `url`을 `파일 시스템` 접두사가 필요 합니다. 예를 들어, `url` 매개 변수 `resolveLocalFileSystemURL`에 대 한 안 드 로이드에서 양식 `file:///persistent/somefile.txt` 반대로 양식 `filesystem:file:///persistent/somefile.txt`에 있어야 합니다. -사용 되지 않는 `toNativeURL` 함수는 지원 되지 않습니다 및 stub에는 없습니다. -`setMetadata` 함수는 규격에 명시 되지 않은 및 지원 되지 않습니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 SYNTAX_ERR(code: 8) 비 existant 파일 시스템의 요청에. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 PATH_EXISTS_ERR(code: 12) 독점적으로 파일 또는 디렉터리를 만들 려,는 이미 존재 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NO_MODIFICATION_ALLOWED_ERR(code: 6) 루트 파일 시스템에 removeRecursively을 호출 하려고 합니다. -INVALID_MODIFICATION_ERR (코드: 9) 대신 throw 됩니다 NOT_FOUND_ERR(code: 1) moveTo 디렉터리 존재 하지 않는 것을 시도에.
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### IndexedDB 기반 구현이 특수 (파이어 폭스와 IE)
+
+* `.` `.`는 지원 되지 않습니다.
+* IE `file:///`를 지원 하지 않습니다-모드; 호스트 모드 지원된 (http://localhost:xxxx)입니다.
+* 파이어 폭스 파일 시스템 크기 제한 이지만 각 50MB 확장 사용자 권한을 요청 합니다. IE10 최대 10 mb 결합 AppCache 및 IndexedDB 묻는 사이트 당 250 mb의 최대 최대 증가 될 수 있도록 하려는 경우 해당 수준에 충돌 한 번 메시지를 표시 하지 않고 파일 시스템의 구현에 사용을 허용 한다. 그래서 `size` 매개 변수 `requestFileSystem` 함수에 대 한 파이어 폭스와 IE에서 파일 시스템 영향을 주지 않습니다.
+* `readAsBinaryString` 함수 사양에 명시 되지 않은 IE에서 지원 되지 않으며 stub에는 없습니다.
+* `file.type`은 항상 null입니다.
+* 하지 항목 삭제 된 DirectoryEntry 인스턴스의 콜백 결과 사용 하 여 만들어야 합니다. 그렇지 않으면, '교수형 항목'을 얻을 것 이다.
+* 그냥 작성 된 파일을 읽을 수 있는이 파일의 새 인스턴스를 얻으려면 해야 합니다.
+* `setMetadata` 함수는 사양에 명시 되지 않은 지원 `modificationTime` 필드 변경에만 해당 합니다.
+* `copyTo` 및 `moveTo` 함수는 디렉터리를 지원 하지 않습니다.
+* 디렉터리 메타 데이터는 지원 되지 않습니다.
+* 둘 다 Entry.remove와 directoryEntry.removeRecursively 비어 있지 않은 디렉터리를 제거할 때 실패 하지 않습니다-디렉터리 제거 되는 대신 내용을 함께 청소.
+* `abort` 및 `truncate` 함수 지원 되지 않습니다.
+* 진행 이벤트가 발생 하지 합니다. 예를 들어,이 처리기 하지 실행 됩니다.
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## 업그레이드 노트
+
+이 플러그인의 v1.0.0에 게시 된 사양에 맞춰 더 많은 것 `FileEntry` 및 `DirectoryEntry` 구조 변경 되었습니다.
+
+플러그인의 이전 (pre-1.0.0) 버전 장치 절대 파일 위치 `Entry` 개체의 `fullPath` 속성에 저장 됩니다. 이러한 경로 일반적으로 같습니다.
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+이러한 경로 `항목` 개체의 `toURL()` 메서드에서 반환 했다.
+
+V1.0.0, `fullPath` 속성은 *HTML 파일 시스템의 루트에 상대적인* 파일의 경로를. 그래서, 위의 경로 지금 둘 다의 `fullPath`와 `FileEntry` 개체에 의해 표현 될 것 이다
+
+ /path/to/file
+
+
+응용 프로그램 작동 장치 절대 경로, 이전 `항목` 개체의 `fullPath` 속성을 통해 그 경로 검색 하는 경우에, 당신은 대신 `entry.toURL()`를 사용 하 여 코드를 업데이트 해야 합니다.
+
+대 한 뒤 호환성, `resolveLocalFileSystemURL()` 메서드는 장치-절대-경로 수락 하 고 그 파일 중 `TEMPORARY` 또는 `PERSISTENT` 파일 시스템 내에서 존재 하는 경우, 해당 `Entry` 개체를 반환 합니다.
+
+이 특히 이전 장치 절대 경로 사용 하는 파일 전송 플러그인에 문제가 있다 (그리고 아직도 그들을 받아들일 수.) 그것은 `entry.toURL()`와 `entry.fullPath`를 대체 확인 장치에 파일을 사용 하는 플러그인을 지 고 그래서 파일 시스템 Url와 함께 제대로 작동 하려면 업데이트 되었습니다.
+
+V1.1.0에 `toURL()`의 반환 값 (\[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394) 참조)로 바뀌었다 'file://' 절대 URL을 반환. 가능 하다 면. 보장 하는 ' cdvfile:'-URL `toInternalURL()`를 지금 사용할 수 있습니다. 이 메서드 이제 양식의 파일 Url을 반환 합니다.
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+어떤 파일을 고유 하 게 식별 하려면 사용할 수 있습니다.
+
+## 오류 코드 및 의미의 목록
+
+오류가 throw 됩니다 때 다음 코드 중 하나가 사용 됩니다.
+
+| 코드 | 상수 |
+| --:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## (선택 사항) 플러그인 구성
+
+사용 가능한 파일 시스템의 집합 플랫폼 당 구성된 될 수 있습니다. IOS와 안 드 로이드를 인식 한 `config.xml` 설치 될 파일 시스템 이름에 태그. 기본적으로 모든 파일 시스템 루트 사용할 수 있습니다.
+
+
+
+
+
+### 안 드 로이드
+
+* `files`: 응용 프로그램의 내부 파일 저장 디렉토리
+* `files-external`: 응용 프로그램의 외부 파일 저장 디렉토리
+* `sdcard`: 글로벌 외부 파일 저장 디렉토리 (이것은 SD 카드의 루트 설치 된 경우). 이것을 사용 하려면 `android.permission.WRITE_EXTERNAL_STORAGE` 권한이 있어야 합니다.
+* `cache`: 응용 프로그램의 내부 캐시 디렉터리
+* `cache-external`: 응용 프로그램의 외부 캐시 디렉터리
+* `root`: 전체 장치 파일 시스템
+
+안 드 로이드는 또한 "파일" 파일 시스템 내에서 "/ 문서 /" 하위 디렉토리를 나타내는 "문서" 라는 특별 한 파일을 지원 합니다.
+
+### iOS
+
+* `library`: 응용 프로그램의 라이브러리 디렉터리
+* `documents`: 응용 프로그램의 문서 디렉토리
+* `cache`: 응용 프로그램의 캐시 디렉터리
+* `bundle`: 응용 프로그램의 번들; (읽기 전용) 디스크에 응용 프로그램 자체의 위치
+* `root`: 전체 장치 파일 시스템
+
+기본적으로 라이브러리 및 문서 디렉토리 iCloud에 동기화 할 수 있습니다. 또한 2 개의 추가적인 파일 시스템, `library-nosync` 및 `documents-nosync`, 내 특별 한 동기화 되지 않은 디렉터리를 대표 하는 요청할 수 있습니다는 `/Library` 또는 `/Documents` 파일 시스템.
diff --git a/plugins/cordova-plugin-file/doc/ko/plugins.md b/plugins/cordova-plugin-file/doc/ko/plugins.md
new file mode 100644
index 0000000..31b274d
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ko/plugins.md
@@ -0,0 +1,101 @@
+
+
+# 플러그인 개발자를 위한 노트
+
+이 노트는 주로 파일 플러그인을 사용 하 여 파일 시스템 플러그인 인터페이스를 작성 하 고 싶은 안 드 로이드와 iOS 개발자를 위한 것입니다.
+
+## 코르 도우 바 파일 시스템 Url 사용
+
+버전 1.0.0, 이후이 플러그인과 Url 사용 하고있다는 `cdvfile` 교량, 모든 통신에 대 한 제도 보다는 자바 원시 장치 파일 시스템 경로 노출.
+
+자바 스크립트 측면에서 즉 그 FileEntry 및 DirectoryEntry 개체 fullPath 속성을 HTML 파일 시스템의 루트에 상대적입니다. FileEntry 또는 DirectoryEntry 개체를 수락 하는 플러그인의 자바 API를 호출 해야 `.toURL()` 다리에 걸쳐 네이티브 코드에 전달 하기 전에 해당 개체에.
+
+### Cdvfile 변환: / / fileystem 경로 Url
+
+플러그인 파일 시스템을 작성 하는 실제 파일 시스템 위치에 받은 파일 시스템 URL을 변환 할 수 있습니다. 이렇게, 네이티브 플랫폼에 따라 여러 방법이 있다.
+
+기억 하는 것이 중요 하다 모든 `cdvfile://` Url은 실제 파일 장치에 매핑. 일부 Url 파일에 의해 표현 되지 않는 또는 심지어 원격 리소스를 참조할 수 있는 장치에 자산을 참조할 수 있습니다. 이러한 가능성 때문에 플러그인 경로를 Url을 변환 하려고 할 때 다시 의미 있는 결과 얻을 지 여부를 항상 테스트 해야 합니다.
+
+#### 안 드 로이드
+
+안 드 로이드, 변환 하는 간단한 방법에는 `cdvfile://` URL을 파일 시스템 경로 사용 하는 `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`처리할 수 있는 여러 가지 방법에는 `cdvfile://` Url:
+
+ webView 플러그인 클래스 CordovaResourceApi resourceApi의 멤버인 = webView.getResourceApi();
+
+ 장치에이 파일을 나타내는 file:/// URL 얻기 / / 같은 URL 변경 파일 Uri fileURL에 매핑할 수 없는 경우 또는 = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+그것은 또한 파일 플러그인을 직접 사용할 수 있습니다:
+
+ 가져오기 org.apache.cordova.file.FileUtils;
+ 가져오기 org.apache.cordova.file.FileSystem;
+ 가져오기 java.net.MalformedURLException;
+
+ 플러그인 관리자에서 파일 플러그인을 얻을 FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ 그것 시도 대 한 경로 얻을 URL을 감안할 때, {문자열 경로 = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / 파일 시스템 url 인식 되지 않았습니다}
+
+
+경로를 변환 하는 `cdvfile://` URL:
+
+ 가져오기 org.apache.cordova.file.LocalFilesystemURL;
+
+ 장치 경로 대 한 LocalFilesystemURL 개체를 가져오기 / / cdvfile URL로 나타낼 수 없는 경우 null.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ URL 개체 문자열 cdvfileURL의 문자열 표현을 = url.toString();
+
+
+플러그인 파일을 만들고 그것에 대 한 FileEntry 개체를 반환 하려면, 파일 플러그인을 사용.
+
+ JSON 구조를 JavaScript에 반환을 위한 적당 한 반환 / /이 파일은 cdvfile URL로 표현 하는 경우 null.
+ JSONObject 항목 = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+IOS에서 코르도바 같은 사용 하지 않는 `CordovaResourceApi` 안 드 로이드 개념. Ios, Url 및 파일 시스템 경로 사이 변환 파일 플러그인을 사용 해야 합니다.
+
+ URL 문자열 CDVFilesystemURL * url에서 CDVFilesystem URL 개체를 가져오기 = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ 파일 NSString * 경로에 매핑할 수 없는 경우 URL 개체 또는 없음에 대 한 경로 얻을 = [filePlugin filesystemPathForURL:url];
+
+
+ 장치 경로 대 한 CDVFilesystem URL 개체를 가져오기 또는 / / 없음 cdvfile URL로 나타낼 수 없는 경우.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ URL 개체 NSString * cdvfileURL의 문자열 표현을 = [url absoluteString];
+
+
+플러그인 파일을 만들고 그것에 대 한 FileEntry 개체를 반환 하려면, 파일 플러그인을 사용.
+
+ 장치 경로 대 한 CDVFilesystem URL 개체를 가져오기 또는 / / 없음 cdvfile URL로 나타낼 수 없는 경우.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ 자바 스크립트 NSDictionary * 항목으로 돌아가려면 구조를 얻을 = [filePlugin makeEntryForLocalURL:url]
+
+
+#### 자바 스크립트
+
+자바 스크립트에는 `cdvfile://` FileEntry 또는 DirectoryEntry 개체에서 URL 호출 `.toURL()` 그것에:
+
+ var cdvfileURL = entry.toURL();
+
+
+플러그인 응답 처리기에서 실제 항목 개체로 반환 된 FileEntry 구조에서 변환 처리기 코드 해야 파일 플러그인 가져오고 새 개체를 만들:
+
+ 적절 한 항목 개체 var 항목;
+ 경우 (entryStruct.isDirectory) {항목 = 새 DirectoryEntry (entryStruct.name, entryStruct.fullPath, 새로운 FileSystem(entryStruct.filesystemName));} 다른 {항목 = 새로운 FileEntry (entryStruct.name, entryStruct.fullPath, 새로운 FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/pl/README.md b/plugins/cordova-plugin-file/doc/pl/README.md
new file mode 100644
index 0000000..166c3ce
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/pl/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+Ten plugin implementuje API pliku, dzięki czemu dostęp do odczytu i zapisu do plików znajdujących się na urządzeniu.
+
+Ten plugin jest oparty na kilka specyfikacje, w tym: HTML5 File API
+
+Katalogi (nieistniejącego już) i System Najnowsze rozszerzenia: , chociaż większość z ten plugin kod został napisany podczas wcześniejszych specyfikacji były aktualne:
+
+To również implementuje specyfikację FileWriter:
+
+Wykorzystania, prosimy odnieść się do skały HTML5 doskonałe [plików art.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+Omówienie innych opcji przechowywania odnoszą się do Cordova z [magazynu przewodnik](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+Ten plugin określa globalne `cordova.file` obiektu.
+
+Chociaż w globalnym zasięgu, to nie dostępne dopiero po `deviceready` imprezie.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Instalacja
+
+ cordova plugin add cordova-plugin-file
+
+
+## Obsługiwane platformy
+
+ * Amazon Fire OS
+ * Android
+ * BlackBerry 10
+ * Firefox OS
+ * iOS
+ * Windows Phone 7 i 8 *
+ * Windows 8 *
+ * Windows*
+ * Przeglądarka
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## Gdzie przechowywać pliki
+
+Od v1.2.0 znajdują się adresy URL do katalogów ważne systemu plików. Każdy adres URL jest w formie *file:///path/to/spot/* i mogą być konwertowane na `DirectoryEntry` za pomocą `window.resolveLocalFileSystemURL()`.
+
+ * `cordova.file.applicationDirectory`-Tylko do odczytu katalogu gdzie jest zainstalowana aplikacja. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.applicationStorageDirectory`-Katalogu obszaru izolowanego aplikacji; na iOS to miejsce jest tylko do odczytu (ale podkatalogów określonego [jak `/Documents` ] są odczytu i zapisu). Wszystkie dane zawarte w jest prywatną do aplikacji. ( *iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.dataDirectory`-Trwałe i prywatne dane magazynowanie w izolowanym aplikacji przy użyciu pamięci wewnętrznej (na Android, jeśli trzeba użyć zewnętrznej pamięci, należy użyć `.externalDataDirectory` ). Na iOS, Katalog ten nie jest zsynchronizowane z iCloud (za pomocą `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.cacheDirectory`-Katalog dla plików buforowanych danych lub pliki, które aplikacji ponownie można łatwo tworzyć. System operacyjny może usunąć te pliki, gdy urządzenie działa niski na przechowywanie, niemniej jednak aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj. (*iOS*, *Android*, *BlackBerry 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-Stosowania przestrzeni na zewnętrznej pamięci masowej. (*Android*)
+
+ * `cordova.file.externalDataDirectory`-Gdzie umieścić pliki danych specyficznych dla aplikacji na zewnętrznej pamięci masowej. (*Android*)
+
+ * `cordova.file.externalCacheDirectory`-Pamięci podręcznej aplikacji na zewnętrznej pamięci masowej. (*Android*)
+
+ * `cordova.file.externalRootDirectory`-Korzeń zewnętrznej pamięci masowej (karty SD). (*Android*, *BlackBerry 10*)
+
+ * `cordova.file.tempDirectory`-Temp katalogu systemu operacyjnego można wyczyścić w będzie. Nie należy polegać na OS wobec usunąć ten katalog; aplikacji należy zawsze usunąć pliki jako obowiązujące. (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-Posiada pliki specyficzne dla aplikacji, które powinny być zsynchronizowane (np. do iCloud). (*iOS*)
+
+ * `cordova.file.documentsDirectory`-Pliki prywatne do aplikacji, ale że mają znaczenie dla innych aplikacji (np. plików pakietu Office). (*iOS*)
+
+ * `cordova.file.sharedDirectory`-Pliki dostępne na całym świecie do wszystkich aplikacji (*BlackBerry 10*)
+
+## Plik System układy
+
+Chociaż technicznie implementacyjnym, może być bardzo przydatne wiedzieć, jak `cordova.file.*` właściwości mapy fizycznej ścieżki na prawdziwe urządzenie.
+
+### iOS układ systemu plików
+
+| Ścieżka urządzenia | `Cordova.File.*` | `iosExtraFileSystems` | r/w? | trwałe? | Czyści OS | Synchronizacja | prywatne |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:--------:|:-------------:|:--------------:|:--------:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/D! | N/D! | N/D! | Tak |
+| `appname.app/` | applicationDirectory | pakiet | r | N/D! | N/D! | N/D! | Tak |
+| `www/` | - | - | r | N/D! | N/D! | N/D! | Tak |
+| `Documents/` | documentsDirectory | dokumenty | r/w | Tak | Nr | Tak | Tak |
+| `NoCloud/` | - | dokumenty nosync | r/w | Tak | Nr | Nr | Tak |
+| `Library` | - | Biblioteka | r/w | Tak | Nr | Tak? | Tak |
+| `NoCloud/` | dataDirectory | Biblioteka nosync | r/w | Tak | Nr | Nr | Tak |
+| `Cloud/` | syncedDataDirectory | - | r/w | Tak | Nr | Tak | Tak |
+| `Caches/` | cacheDirectory | pamięci podręcznej | r/w | Tak * | Yes**\* | Nr | Tak |
+| `tmp/` | tempDirectory | - | r/w | No** | Yes**\* | Nr | Tak |
+
+\ * Pliki utrzymywały aplikacja zostanie ponownie uruchomiony i uaktualnienia, ale w tym katalogu mogą być rozliczone przy każdym OS pragnień. Aplikacji należy umożliwić odtworzenie treści, które mogą być usunięte.
+
+** Plików może utrzymywać się po ponownym uruchomieniu aplikacji, ale nie opierają się na tym zachowaniu. Pliki nie są gwarantowane w aktualizacji. Aplikacji należy usunąć pliki z tego katalogu, gdy ma to zastosowanie, ponieważ system operacyjny nie gwarantuje Kiedy (lub nawet jeśli) te pliki zostaną usunięte.
+
+**\ * System operacyjny może wyczyścić zawartość tego katalogu, gdy czuje, że jest to konieczne, ale nie powoływać się na to. Należy wyczyścić ten katalog jako odpowiednie dla aplikacji.
+
+### Układ systemu Android plików
+
+| Ścieżka urządzenia | `Cordova.File.*` | `AndroidExtraFileSystems` | r/w? | trwałe? | Czyści OS | prywatne |
+|:------------------------------------------------ |:----------------------------------- |:------------------------------- |:----:|:-------:|:---------:|:--------:|
+| `file:///android_asset/` | applicationDirectory | | r | N/D! | N/D! | Tak |
+| `/Data/danych/< Aplikacja id > /` | applicationStorageDirectory | - | r/w | N/D! | N/D! | Tak |
+| `cache` | cacheDirectory | pamięci podręcznej | r/w | Tak | Yes\ * | Tak |
+| `files` | dataDirectory | pliki | r/w | Tak | Nr | Tak |
+| `Documents` | | dokumenty | r/w | Tak | Nr | Tak |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Tak | Nr | Nr |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Tak | Nr | Nr |
+| `cache` | externalCacheDirectry | zewnętrznych pamięci podręcznej | r/w | Tak | No** | Nr |
+| `files` | externalDataDirectory | zewnętrznych plików | r/w | Tak | Nr | Nr |
+
+\ * OS może okresowo usunąć ten katalog, ale nie opierają się na tym zachowaniu. Wyczyść zawartość tego katalogu jako odpowiednie dla danej aplikacji. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość w tym katalogu są usuwane.
+
+** OS nie usunąć ten katalog automatycznie; Jesteś odpowiedzialny za zarządzanie zawartość siebie. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość katalogu są usuwane.
+
+**Uwaga**: Jeśli nie mogą być montowane pamięci masowej, właściwości `cordova.file.external*` są `wartości null`.
+
+### Układ systemu plików blackBerry 10
+
+| Ścieżka urządzenia | `Cordova.File.*` | r/w? | trwałe? | Czyści OS | prywatne |
+|:----------------------------------------------------------- |:--------------------------- |:----:|:-------:|:---------:|:--------:|
+| `file:///accounts/1000/AppData/ < id aplikacji > /` | applicationStorageDirectory | r | N/D! | N/D! | Tak |
+| `app/native` | applicationDirectory | r | N/D! | N/D! | Tak |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Nr | Tak | Tak |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Tak | Nr | Tak |
+| `file:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Tak | Nr | Nr |
+| `file:///accounts/1000/Shared` | sharedDirectory | r/w | Tak | Nr | Nr |
+
+*Uwaga*: gdy aplikacja jest rozmieszczana do pracy obwodu, wszystkie ścieżki są względne do /accounts/1000-enterprise.
+
+## Dziwactwa Androida
+
+### Lokalizacja przechowywania trwałych Android
+
+Istnieje wiele prawidłowe lokalizacje do przechowywania trwałych plików na telefonie z systemem Android. Zobacz [tę stronę](http://developer.android.com/guide/topics/data/data-storage.html) do szerokiej dyskusji o różnych możliwościach.
+
+Poprzednie wersje pluginu wybrać lokalizację plików tymczasowych i trwałe podczas uruchamiania, czy urządzenie twierdził, że karta SD (lub równoważne magazynowanie podzia³) był montowany w oparciu. Czy karta SD została zamontowana, czy duży wewnętrzny magazynowanie podzia³ był dostępny (takie jak na Nexus urządzenia,) a następnie trwałe pliki będą przechowywane w katalogu głównego tego miejsca. Oznaczało to, że wszystkie aplikacje Cordova może Zobacz wszystkie pliki dostępne na karcie.
+
+Jeśli karta SD nie był dostępny, a następnie poprzednie wersje będzie przechowywać dane w `/data/data/`, która izoluje aplikacje od siebie, ale nadal może spowodować danych, które mają być współużytkowane przez użytkowników.
+
+Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w lokalizacji magazynu plików, lub przy użyciu poprzednich logiki, z preferencją w aplikacji w pliku `config.xml`. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`:
+
+
+
+
+
+
+Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona.
+
+Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do "Internal" oznacza, że istniejących użytkowników, którzy ich aplikacja może być niesłabnący wobec dostęp ich wcześniej zapisane pliki, w zależności od ich urządzenie.
+
+Jeśli aplikacja jest nowy, lub ma nigdy wcześniej przechowywane pliki w systemie plików trwałe, ustawienie `Internal` generalnie jest zalecane.
+
+### Powolny cyklicznych operacji dla /android_asset
+
+Lista katalogów aktywów jest bardzo powolny na Android. Można przyspieszyć to się jednak przez dodanie `src/android/build-extras.gradle` do katalogu głównego projektu android (również wymaga cordova-android@4.0.0 lub większej).
+
+## Dziwactwa iOS
+
+ * `cordova.file.applicationStorageDirectory`jest tylko do odczytu; próby przechowywania plików w katalogu głównym zakończy się niepowodzeniem. Użyj jednego z innych `cordova.file.*` właściwości zdefiniowane dla iOS (tylko `applicationDirectory` i `applicationStorageDirectory` są tylko do odczytu).
+ * `FileReader.readAsText(blob, encoding)`
+ * `encoding`Parametr nie jest obsługiwana, i kodowanie UTF-8 jest zawsze w efekcie.
+
+### iOS lokalizacja przechowywania trwałych
+
+Istnieją dwa ważne miejsca trwałe pliki na urządzenia iOS: katalogu dokumentów i katalogu biblioteki. Poprzednie wersje pluginu tylko kiedykolwiek przechowywane trwałe pliki w katalogu dokumentów. To miał ten efekt uboczny od rozpoznawalności wszystkie pliki aplikacji w iTunes, który był często niezamierzone, zwłaszcza dla aplikacji, które obsługują wiele małych plików, zamiast produkuje kompletne dokumenty do wywozu, który jest przeznaczenie katalogu.
+
+Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w dokumentach lub katalogu biblioteki, z preferencją w pliku `config.xml` aplikacji. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`:
+
+
+
+
+
+
+Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona.
+
+Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do `Library` oznaczałoby, że istniejących użytkowników, którzy ich aplikacja będzie niesłabnący wobec dostęp ich wcześniej zapisane pliki.
+
+Jeśli aplikacja jest nowy, lub nigdy wcześniej przechowywane pliki w trwałych plików, ustawień `Library` ogólnie jest zalecane.
+
+## Firefox OS dziwactwa
+
+API systemu plików nie jest obsługiwany macierzyście przez Firefox OS i jest zaimplementowany jako podkładki na indexedDB.
+
+ * Nie usuwając niepuste katalogi
+ * Nie obsługuje metadane dla katalogów
+ * Metody `copyTo` i `moveTo` nie obsługuje katalogi
+
+Obsługiwane są następujące ścieżki danych: * `applicationDirectory` - używa `xhr`, aby uzyskać lokalne pliki, które są pakowane z aplikacji. * `dataDirectory` - na trwałe dane specyficzne dla aplikacji pliki. * `cacheDirectory` - buforowanych plików, które powinny przetrwać ponowne uruchomienie aplikacji (aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj).
+
+## Quirks przeglądarki
+
+### Wspólne dziwactw i uwagi
+
+ * Każda przeglądarka używa własnej piaskownicy plików. IE i Firefox Użyj IndexedDB jako podstawa. Wszystkie przeglądarki za pomocą ukośnika jako separatora katalogu ścieżka.
+ * Wpisy w katalogu mają być tworzone sukcesywnie. Na przykład wywołanie `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` zakończy się niepowodzeniem, jeśli nie istnieje dir1.
+ * Plugin żądania użytkownika uprawnień do używania trwałe przechowywanie przy pierwszym uruchomieniu aplikacji.
+ * Wtyczka obsługuje `cdvfile://localhost` (lokalne zasoby) tylko. Czyli zewnętrznych zasobów nie są obsługiwane przez `cdvfile`.
+ * Plugin nie następować po ["Plik API systemu nazw 8.3 ograniczenia"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
+ * Obiektu BLOB i pliku "`close` funkcja nie jest obsługiwana.
+ * `FileSaver` i `BlobBuilder` nie są obsługiwane przez ten plugin i nie ma artykułów.
+ * Plugin nie obsługuje `requestAllFileSystems`. Ta funkcja jest również brak w specyfikacji.
+ * Wpisy w katalogu nie zostaną usunięte, jeśli używasz `create: true` flaga dla istniejącego katalogu.
+ * Pliki utworzone za pomocą konstruktora nie są obsługiwane. Zamiast tego należy użyć metody entry.file.
+ * Każda przeglądarka używa własnej postaci URL odwołania blob.
+ * `readAsDataURL` funkcja jest obsługiwana, ale mediatype w Chrome zależy od wejścia z rozszerzeniem, mediatype w IE zawsze jest pusty (który jest taki sam jak `zwykły tekst` według specyfikacji), mediatype w Firefox jest zawsze `aplikacji/oktet strumień`. Na przykład, jeśli treść jest `abcdefg` Firefox wraca z `danych: stosowanie / octet-stream, base64, YWJjZGVmZw ==`, czyli zwraca `danych:; base64, YWJjZGVmZw ==`, Chrome zwraca `danych: < mediatype w zależności od rozszerzenia nazwy; > base64, YWJjZGVmZw ==`.
+ * `toInternalURL` zwraca ścieżkę w postaci `file:///persistent/path/to/entry` (Firefox, IE). Chrom zwraca ścieżkę w postaci `cdvfile://localhost/persistent/file`.
+
+### Dziwactwa chrom
+
+ * Chrom plików nie jest od razu gotowy po gotowe urządzenia. Jako rozwiązanie alternatywne można subskrybować zdarzenia `filePluginIsReady`. Przykład:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+Funkcja `window.isFilePluginReadyRaised` służy do sprawdzenia, czy zdarzenie już została podniesiona. -kwoty plików tymczasowych i trwałe window.requestFileSystem nie są ograniczone w Chrome. -W celu zwiększenia trwałego magazynu w Chrome, należy wywołać metodę `window.initPersistentFileSystem`. Domyślnie trwałe dyskowa jest 5 MB. -Chrome wymaga `--pozwalają--dostęp z plików` uruchomić argument na poparcie API za pośrednictwem protokołu `file:///`. -`Plik` obiekt będzie nie zmieniło jeśli flaga `{create:true}` gdy już istniejący `wpis`. -wydarzenia `zwrotu` właściwość jest zestaw true w Chrome. Jest to sprzeczne ze [specyfikacji](http://dev.w3.org/2009/dap/file-system/file-writer.html). -Funkcja `toURL` w Chrome zwraca `plików:`-poprzedzona ścieżką w zależności od aplikacji hosta. Na przykład, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -wynik funkcji `toURL` nie zawierają ukośnika w wpis w katalogu. Chrom usuwa katalogi z ciąć doczepiane adresów URL poprawnie choć. -Metoda `resolveLocalFileSystemURL` wymaga przychodzących `url` mają prefiks `plików`. Na przykład parametr `adresu url` do `resolveLocalFileSystemURL` powinny być w formie `filesystem:file:///persistent/somefile.txt`, w przeciwieństwie do formularza `file:///persistent/somefile.txt` w Android. -Przestarzałe `toNativeURL` funkcja nie jest obsługiwana i nie tylko. -Funkcja `setMetadata` jest nie podane w specyfikacji i nie jest obsługiwane. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast SYNTAX_ERR(code: 8) na żądanie nieistniejącą plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast PATH_EXISTS_ERR(code: 12) próbuje stworzyć wyłącznie pliku lub katalogu, który już istnieje. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NO_MODIFICATION_ALLOWED_ERR(code: 6) na próby wywołania removeRecursively w głównym systemie plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NOT_FOUND_ERR(code: 1) na trudny do katalogu moveTo, który nie istnieje.
+
+### Na bazie IndexedDB impl dziwactw (Firefox i IE)
+
+ * `.` i `.` nie są obsługiwane.
+ * IE obsługuje `file:///`-tryb; tylko obsługiwane tryb jest obsługiwany (http://localhost:xxxx).
+ * Rozmiar plików Firefox nie jest ograniczona, ale każde rozszerzenie 50MB zwróci użytkownikowi uprawnienia. IE10 pozwala maksymalnie 10mb połączone "appcache" i IndexedDB używane w implementacji systemu plików bez monitowania, gdy trafisz na tym poziomie, które uzyskasz, jeśli chcesz mogła ona zostać zwiększony do max 250mb na stronie. Więc `rozmiar` parametru funkcja `requestFileSystem` nie wpływa na system plików Firefox i IE.
+ * `readAsBinaryString` funkcja nie jest określona w specyfikacji i nie obsługiwane w IE i nie tylko.
+ * `File.Type` ma zawsze wartość null.
+ * Nie należy utworzyć wpis za pomocą DirectoryEntry wystąpienie wynik wywołania zwrotnego, który został usunięty. W przeciwnym razie dostaniesz wpisem"wiszące".
+ * Zanim będzie można przeczytać plik, który został napisany tylko trzeba uzyskać nowe wystąpienie tego pliku.
+ * Funkcja `setMetadata`, która nie jest określona w specyfikacji obsługuje tylko zmian pola `modificationTime`.
+ * `copyTo` i `moveTo` funkcji nie obsługuje katalogi.
+ * Metadanych w katalogów nie jest obsługiwana.
+ * Zarówno Entry.remove i directoryEntry.removeRecursively nie usuwając niepuste katalogi - katalogi są usuwane są czyszczone z treści zamiast.
+ * `abort` i `truncate` funkcje nie są obsługiwane.
+ * zdarzenia postępu nie są zwalniani. Na przykład to obsługa będzie nie wykonywane:
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## Uaktualniania notatek
+
+W v1.0.0 tego pluginu struktury `FileEntry` i `DirectoryEntry` zmieniły się więcej zgodnie z opublikowaną specyfikacją.
+
+Poprzednie wersje (pre-1.0.0) plugin przechowywane urządzenia bezwzględna plik lokalizacja we właściwości `fullPath` `wpis` obiektów. Te ścieżki zazwyczaj będzie wyglądać
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Te ścieżki były także zwracany przez metodę `toURL()` `Entry` obiektów.
+
+Z v1.0.0 atrybut `fullPath` jest ścieżką do pliku, *względem katalogu głównego systemu plików HTML*. Tak powyżej ścieżki będzie teraz zarówno być reprezentowane przez obiekt `FileEntry` z `fullPath` o
+
+ /path/to/file
+
+
+Jeśli aplikacja działa z ścieżki bezwzględnej urządzeń, i możesz wcześniej źródło tych ścieżek przez właściwość `fullPath` `wpis` obiektów, należy zaktualizować kod, aby zamiast tego użyj `entry.toURL()`.
+
+Dla wstecznej kompatybilności, Metoda `resolveLocalFileSystemURL()` będzie zaakceptować urządzenia ścieżka bezwzględna i zwróci obiekt `Entry` odpowiadający, tak długo, jak ten plik istnieje w albo `TEMPORARY` lub `PERSISTENT` systemy plików.
+
+To szczególnie został problem z pluginem transferu plików, które poprzednio używane ścieżki bezwzględnej urządzeń (i wciąż można je przyjąć). Została zaktualizowana do pracy poprawnie z adresów URL plików, więc wymiana `entry.fullPath` z `entry.toURL()` powinno rozwiązać wszelkie problemy dostawanie ten plugin do pracy z plików w pamięci urządzenia.
+
+W v1.1.0 wartość zwracana przez `toURL()` został zmieniony (patrz \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) zwraca adres URL absolutnej "file://". wszędzie tam, gdzie jest to możliwe. Aby zapewnić ' cdvfile:'-URL można użyć `toInternalURL()` teraz. Ta metoda zwróci teraz adresy URL plików formularza
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+który służy do jednoznacznej identyfikacji pliku.
+
+## Wykaz kodów błędów i ich znaczenie
+
+Gdy błąd jest generowany, jeden z następujących kodów będzie służyć.
+
+| Kod | Stała |
+| ---:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Konfigurowanie wtyczka (opcjonalny)
+
+Zestaw dostępnych plików może być skonfigurowany na platformie. Zarówno iOS i Android Tag w `pliku config.xml`, których nazwy plików do instalacji. Domyślnie włączone są wszystkie korzenie systemu plików.
+
+
+
+
+
+### Android
+
+ * `files`: katalogu przechowywania plików aplikacji
+ * `files-external`: katalog aplikacji zewnętrznych plików
+ * `sdcard`: katalog globalny plik zewnętrzny (to jest głównym karty SD, jeśli jedna jest zainstalowana). Musi mieć uprawnienia `android.permission.WRITE_EXTERNAL_STORAGE` wobec używać ten.
+ * `cache`: katalogu wewnętrznej pamięci podręcznej aplikacji
+ * `cache-external`: katalogu aplikacji zewnętrznych pamięci podręcznej
+ * `root`: całe urządzenie systemu plików
+
+Android obsługuje również specjalnych plików o nazwie "dokumenty", który reprezentuje podkatalog "/ dokumenty /" w ramach systemu plików "pliki".
+
+### iOS
+
+ * `library`: katalog biblioteki aplikacji
+ * `documents`: dokumenty katalogu aplikacji
+ * `cache`: katalogu pamięci podręcznej aplikacji
+ * `bundle`: pakiet aplikacji; Lokalizacja aplikacji na dysku (tylko do odczytu)
+ * `root`: całe urządzenie systemu plików
+
+Domyślnie katalogi biblioteki i dokumenty mogą być synchronizowane iCloud. Można również zażądać dwóch dodatkowych plików, `library-nosync` i `documents-nosync`, które stanowią specjalny katalog nie zsynchronizowane w `/Library` lub systemu plików `/Documents`.
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/pl/index.md b/plugins/cordova-plugin-file/doc/pl/index.md
new file mode 100644
index 0000000..1ccb330
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/pl/index.md
@@ -0,0 +1,338 @@
+
+
+# cordova-plugin-file
+
+Ten plugin implementuje API pliku, dzięki czemu dostęp do odczytu i zapisu do plików znajdujących się na urządzeniu.
+
+Ten plugin jest oparty na kilka specyfikacje, w tym: HTML5 File API
+
+Katalogi (nieistniejącego już) i System Najnowsze rozszerzenia: , chociaż większość z ten plugin kod został napisany podczas wcześniejszych specyfikacji były aktualne:
+
+To również implementuje specyfikację FileWriter:
+
+Wykorzystania, prosimy odnieść się do skały HTML5 doskonałe [plików art.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+Omówienie innych opcji przechowywania odnoszą się do Cordova z [magazynu przewodnik][2].
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+Ten plugin określa globalne `cordova.file` obiektu.
+
+Chociaż w globalnym zasięgu, to nie dostępne dopiero po `deviceready` imprezie.
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## Instalacja
+
+ cordova plugin add cordova-plugin-file
+
+
+## Obsługiwane platformy
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Firefox OS
+* iOS
+* Windows Phone 7 i 8 *
+* Windows 8 *
+* Przeglądarka
+
+* *Nie obsługują tych platform, `FileReader.readAsArrayBuffer` ani `FileWriter.write(blob)`.*
+
+## Gdzie przechowywać pliki
+
+Od v1.2.0 znajdują się adresy URL do katalogów ważne systemu plików. Każdy adres URL jest w formie *file:///path/to/spot/* i mogą być konwertowane na `DirectoryEntry` za pomocą `window.resolveLocalFileSystemURL()`.
+
+* `cordova.file.applicationDirectory`-Tylko do odczytu katalogu gdzie jest zainstalowana aplikacja. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.applicationStorageDirectory`-Katalogu obszaru izolowanego aplikacji; na iOS to miejsce jest tylko do odczytu (ale podkatalogów określonego [jak `/Documents` ] są odczytu i zapisu). Wszystkie dane zawarte w jest prywatną do aplikacji. ( *iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.dataDirectory`-Trwałe i prywatne dane magazynowanie w izolowanym aplikacji przy użyciu pamięci wewnętrznej (na Android, jeśli trzeba użyć zewnętrznej pamięci, należy użyć `.externalDataDirectory` ). Na iOS, Katalog ten nie jest zsynchronizowane z iCloud (za pomocą `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.cacheDirectory`-Katalog dla plików buforowanych danych lub pliki, które aplikacji ponownie można łatwo tworzyć. System operacyjny może usunąć te pliki, gdy urządzenie działa niski na przechowywanie, niemniej jednak aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-Stosowania przestrzeni na zewnętrznej pamięci masowej. (*Android*)
+
+* `cordova.file.externalDataDirectory`-Gdzie umieścić pliki danych specyficznych dla aplikacji na zewnętrznej pamięci masowej. (*Android*)
+
+* `cordova.file.externalCacheDirectory`-Pamięci podręcznej aplikacji na zewnętrznej pamięci masowej. (*Android*)
+
+* `cordova.file.externalRootDirectory`-Korzeń zewnętrznej pamięci masowej (karty SD). (*Android*, *BlackBerry 10*)
+
+* `cordova.file.tempDirectory`-Temp katalogu systemu operacyjnego można wyczyścić w będzie. Nie należy polegać na OS wobec usunąć ten katalog; aplikacji należy zawsze usunąć pliki jako obowiązujące. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-Posiada pliki specyficzne dla aplikacji, które powinny być zsynchronizowane (np. do iCloud). (*iOS*)
+
+* `cordova.file.documentsDirectory`-Pliki prywatne do aplikacji, ale że mają znaczenie dla innych aplikacji (np. plików pakietu Office). (*iOS*)
+
+* `cordova.file.sharedDirectory`-Pliki dostępne na całym świecie do wszystkich aplikacji (*BlackBerry 10*)
+
+## Plik System układy
+
+Chociaż technicznie implementacyjnym, może być bardzo przydatne wiedzieć, jak `cordova.file.*` właściwości mapy fizycznej ścieżki na prawdziwe urządzenie.
+
+### iOS układ systemu plików
+
+| Ścieżka urządzenia | `Cordova.File.*` | `iosExtraFileSystems` | r/w? | trwałe? | Czyści OS | Synchronizacja | prywatne |
+|:-------------------------------------------- |:--------------------------- |:--------------------- |:----:|:-------:|:-----------:|:--------------:|:--------:|
+| `/ var/mobile/Applications/< UUID > /` | applicationStorageDirectory | - | r | N/D! | N/D! | N/D! | Tak |
+| `appname.app/` | applicationDirectory | pakiet | r | N/D! | N/D! | N/D! | Tak |
+| `www/` | - | - | r | N/D! | N/D! | N/D! | Tak |
+| `Documents/` | documentsDirectory | dokumenty | r/w | Tak | Nr | Tak | Tak |
+| `NoCloud/` | - | dokumenty nosync | r/w | Tak | Nr | Nr | Tak |
+| `Library` | - | Biblioteka | r/w | Tak | Nr | Tak? | Tak |
+| `NoCloud/` | dataDirectory | Biblioteka nosync | r/w | Tak | Nr | Nr | Tak |
+| `Cloud/` | syncedDataDirectory | - | r/w | Tak | Nr | Tak | Tak |
+| `Caches/` | cacheDirectory | pamięci podręcznej | r/w | Tak * | Tak * * *| | Nr | Tak |
+| `tmp/` | tempDirectory | - | r/w | Nie * * | Tak * * *| | Nr | Tak |
+
+* Pliki utrzymywały aplikacja zostanie ponownie uruchomiony i uaktualnienia, ale w tym katalogu mogą być rozliczone, gdy OS pragnienia. Aplikacji powinny być w stanie odtworzyć zawartość, która może być usunięta.
+
+* * Plików może utrzymywać się po ponownym uruchomieniu aplikacji, ale nie opierają się na tym zachowaniu. Pliki nie są gwarantowane w aktualizacji. Aplikacji należy usunąć pliki z tego katalogu, gdy ma to zastosowanie, ponieważ system operacyjny nie gwarantuje Kiedy (lub nawet jeśli) te pliki zostaną usunięte.
+
+* * *| System operacyjny może wyczyścić zawartość w tym katalogu, gdy czuje, że jest to konieczne, ale nie powoływać się na to. Należy wyczyścić ten katalog jako odpowiednie dla aplikacji.
+
+### Układ systemu Android plików
+
+| Ścieżka urządzenia | `Cordova.File.*` | `AndroidExtraFileSystems` | r/w? | trwałe? | Czyści OS | prywatne |
+|:--------------------------------------- |:----------------------------------- |:------------------------------- |:----:|:-------:|:---------:|:--------:|
+| `file:///android_asset/` | applicationDirectory | | r | N/D! | N/D! | Tak |
+| `/Data/danych/< Aplikacja id > /` | applicationStorageDirectory | - | r/w | N/D! | N/D! | Tak |
+| `cache` | cacheDirectory | pamięci podręcznej | r/w | Tak | Tak * | Tak |
+| `files` | dataDirectory | pliki | r/w | Tak | Nr | Tak |
+| `Documents` | | dokumenty | r/w | Tak | Nr | Tak |
+| `< sdcard > /` | externalRootDirectory | sdcard | r/w | Tak | Nr | Nr |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Tak | Nr | Nr |
+| `cache` | externalCacheDirectry | zewnętrznych pamięci podręcznej | r/w | Tak | Nie * * | Nr |
+| `files` | externalDataDirectory | zewnętrznych plików | r/w | Tak | Nr | Nr |
+
+* System operacyjny może okresowo usunąć ten katalog, ale nie opierają się na tym zachowaniu. Wyczyść zawartość tego katalogu jako odpowiednie dla danej aplikacji. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość w tym katalogu są usuwane.
+
+* * System operacyjny nie usunąć ten katalog automatycznie; Jesteś odpowiedzialny za zarządzanie zawartość siebie. Należy użytkownik przeczyścić pamięć podręczną ręcznie, zawartość katalogu są usuwane.
+
+**Uwaga**: Jeśli nie mogą być montowane pamięci masowej, właściwości `cordova.file.external*` są `wartości null`.
+
+### Układ systemu plików blackBerry 10
+
+| Ścieżka urządzenia | `Cordova.File.*` | r/w? | trwałe? | Czyści OS | prywatne |
+|:--------------------------------------------------------- |:--------------------------- |:----:|:-------:|:---------:|:--------:|
+| `file:///accounts/1000/AppData/ < id aplikacji > /` | applicationStorageDirectory | r | N/D! | N/D! | Tak |
+| `app/native` | applicationDirectory | r | N/D! | N/D! | Tak |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Nr | Tak | Tak |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Tak | Nr | Tak |
+| `file:///accounts/1000/Removable/sdcard` | externalRemovableDirectory | r/w | Tak | Nr | Nr |
+| `file:///accounts/1000/Shared` | sharedDirectory | r/w | Tak | Nr | Nr |
+
+*Uwaga*: gdy aplikacja jest rozmieszczana do pracy obwodu, wszystkie ścieżki są względne do /accounts/1000-enterprise.
+
+## Dziwactwa Androida
+
+### Lokalizacja przechowywania trwałych Android
+
+Istnieje wiele prawidłowe lokalizacje do przechowywania trwałych plików na telefonie z systemem Android. Zobacz [tę stronę][3] do szerokiej dyskusji o różnych możliwościach.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+Poprzednie wersje pluginu wybrać lokalizację plików tymczasowych i trwałe podczas uruchamiania, czy urządzenie twierdził, że karta SD (lub równoważne magazynowanie podzia³) był montowany w oparciu. Czy karta SD została zamontowana, czy duży wewnętrzny magazynowanie podzia³ był dostępny (takie jak na Nexus urządzenia,) a następnie trwałe pliki będą przechowywane w katalogu głównego tego miejsca. Oznaczało to, że wszystkie aplikacje Cordova może Zobacz wszystkie pliki dostępne na karcie.
+
+Jeśli karta SD nie był dostępny, a następnie poprzednie wersje będzie przechowywać dane w `/data/data/`, która izoluje aplikacje od siebie, ale nadal może spowodować danych, które mają być współużytkowane przez użytkowników.
+
+Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w lokalizacji magazynu plików, lub przy użyciu poprzednich logiki, z preferencją w aplikacji w pliku `config.xml`. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`:
+
+
+
+
+
+
+Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona.
+
+Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do "Internal" oznacza, że istniejących użytkowników, którzy ich aplikacja może być niesłabnący wobec dostęp ich wcześniej zapisane pliki, w zależności od ich urządzenie.
+
+Jeśli aplikacja jest nowy, lub ma nigdy wcześniej przechowywane pliki w systemie plików trwałe, ustawienie `Internal` generalnie jest zalecane.
+
+## Dziwactwa iOS
+
+* `cordova.file.applicationStorageDirectory`jest tylko do odczytu; próby przechowywania plików w katalogu głównym zakończy się niepowodzeniem. Użyj jednego z innych `cordova.file.*` właściwości zdefiniowane dla iOS (tylko `applicationDirectory` i `applicationStorageDirectory` są tylko do odczytu).
+* `FileReader.readAsText(blob, encoding)`
+ * `encoding`Parametr nie jest obsługiwana, i kodowanie UTF-8 jest zawsze w efekcie.
+
+### iOS lokalizacja przechowywania trwałych
+
+Istnieją dwa ważne miejsca trwałe pliki na urządzenia iOS: katalogu dokumentów i katalogu biblioteki. Poprzednie wersje pluginu tylko kiedykolwiek przechowywane trwałe pliki w katalogu dokumentów. To miał ten efekt uboczny od rozpoznawalności wszystkie pliki aplikacji w iTunes, który był często niezamierzone, zwłaszcza dla aplikacji, które obsługują wiele małych plików, zamiast produkuje kompletne dokumenty do wywozu, który jest przeznaczenie katalogu.
+
+Teraz jest możliwe, aby zdecydować, czy do przechowywania plików w dokumentach lub katalogu biblioteki, z preferencją w pliku `config.xml` aplikacji. Aby to zrobić, Dodaj jedną z tych dwóch linii do `pliku config.xml`:
+
+
+
+
+
+
+Bez tej linii wtyczki pliku będzie używać `Compatibility` jako domyślny. Jeśli znacznik preferencji jest obecny i to nie jedną z tych wartości, aplikacja nie zostanie uruchomiona.
+
+Jeśli aplikacja wcześniej zostało wysłane do użytkowników, przy użyciu starszych (pre-1.0) wersję tego pluginu i ma zapisane na dysku pliki w trwałych plików, a następnie należy ustawić preferencje do `Compatibility`. Przełączania lokalizacji do `Library` oznaczałoby, że istniejących użytkowników, którzy ich aplikacja będzie niesłabnący wobec dostęp ich wcześniej zapisane pliki.
+
+Jeśli aplikacja jest nowy, lub nigdy wcześniej przechowywane pliki w trwałych plików, ustawień `Library` ogólnie jest zalecane.
+
+## Firefox OS dziwactwa
+
+API systemu plików nie jest obsługiwany macierzyście przez Firefox OS i jest zaimplementowany jako podkładki na indexedDB.
+
+* Nie usuwając niepuste katalogi
+* Nie obsługuje metadane dla katalogów
+* Metody `copyTo` i `moveTo` nie obsługuje katalogi
+
+Obsługiwane są następujące ścieżki danych: * `applicationDirectory` - używa `xhr`, aby uzyskać lokalne pliki, które są pakowane z aplikacji. * `dataDirectory` - na trwałe dane specyficzne dla aplikacji pliki. * `cacheDirectory` - buforowanych plików, które powinny przetrwać ponowne uruchomienie aplikacji (aplikacje nie powinny polegać na OS, aby usunąć pliki tutaj).
+
+## Quirks przeglądarki
+
+### Wspólne dziwactw i uwagi
+
+* Każda przeglądarka używa własnej piaskownicy plików. IE i Firefox Użyj IndexedDB jako podstawa. Wszystkie przeglądarki za pomocą ukośnika jako separatora katalogu ścieżka.
+* Wpisy w katalogu mają być tworzone sukcesywnie. Na przykład wywołanie `fs.root.getDirectory (' dir1/dir2 ', {create:true}, successCallback, errorCallback)` zakończy się niepowodzeniem, jeśli nie istnieje dir1.
+* Plugin żądania użytkownika uprawnień do używania trwałe przechowywanie przy pierwszym uruchomieniu aplikacji.
+* Wtyczka obsługuje `cdvfile://localhost` (lokalne zasoby) tylko. Czyli zewnętrznych zasobów nie są obsługiwane przez `cdvfile`.
+* Plugin nie następować po ["Plik API systemu nazw 8.3 ograniczenia"][4].
+* Obiektu BLOB i pliku "`close` funkcja nie jest obsługiwana.
+* `FileSaver` i `BlobBuilder` nie są obsługiwane przez ten plugin i nie ma artykułów.
+* Plugin nie obsługuje `requestAllFileSystems`. Ta funkcja jest również brak w specyfikacji.
+* Wpisy w katalogu nie zostaną usunięte, jeśli używasz `create: true` flaga dla istniejącego katalogu.
+* Pliki utworzone za pomocą konstruktora nie są obsługiwane. Zamiast tego należy użyć metody entry.file.
+* Każda przeglądarka używa własnej postaci URL odwołania blob.
+* `readAsDataURL` funkcja jest obsługiwana, ale mediatype w Chrome zależy od wejścia z rozszerzeniem, mediatype w IE zawsze jest pusty (który jest taki sam jak `zwykły tekst` według specyfikacji), mediatype w Firefox jest zawsze `aplikacji/oktet strumień`. Na przykład, jeśli treść jest `abcdefg` Firefox wraca z `danych: stosowanie / octet-stream, base64, YWJjZGVmZw ==`, czyli zwraca `danych:; base64, YWJjZGVmZw ==`, Chrome zwraca `danych: < mediatype w zależności od rozszerzenia nazwy; > base64, YWJjZGVmZw ==`.
+* `toInternalURL` zwraca ścieżkę w postaci `file:///persistent/path/to/entry` (Firefox, IE). Chrom zwraca ścieżkę w postaci `cdvfile://localhost/persistent/file`.
+
+ [4]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### Dziwactwa chrom
+
+* Chrom plików nie jest od razu gotowy po gotowe urządzenia. Jako rozwiązanie alternatywne można subskrybować zdarzenia `filePluginIsReady`. Przykład:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+Funkcja `window.isFilePluginReadyRaised` służy do sprawdzenia, czy zdarzenie już została podniesiona. -kwoty plików tymczasowych i trwałe window.requestFileSystem nie są ograniczone w Chrome. -W celu zwiększenia trwałego magazynu w Chrome, należy wywołać metodę `window.initPersistentFileSystem`. Domyślnie trwałe dyskowa jest 5 MB. -Chrome wymaga `--pozwalają--dostęp z plików` uruchomić argument na poparcie API za pośrednictwem protokołu `file:///`. -`Plik` obiekt będzie nie zmieniło jeśli flaga `{create:true}` gdy już istniejący `wpis`. -wydarzenia `zwrotu` właściwość jest zestaw true w Chrome. Jest to sprzeczne ze [specyfikacji][5]. -Funkcja `toURL` w Chrome zwraca `plików:`-poprzedzona ścieżką w zależności od aplikacji hosta. Na przykład, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`. -wynik funkcji `toURL` nie zawierają ukośnika w wpis w katalogu. Chrom usuwa katalogi z ciąć doczepiane adresów URL poprawnie choć. -Metoda `resolveLocalFileSystemURL` wymaga przychodzących `url` mają prefiks `plików`. Na przykład parametr `adresu url` do `resolveLocalFileSystemURL` powinny być w formie `filesystem:file:///persistent/somefile.txt`, w przeciwieństwie do formularza `file:///persistent/somefile.txt` w Android. -Przestarzałe `toNativeURL` funkcja nie jest obsługiwana i nie tylko. -Funkcja `setMetadata` jest nie podane w specyfikacji i nie jest obsługiwane. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast SYNTAX_ERR(code: 8) na żądanie nieistniejącą plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast PATH_EXISTS_ERR(code: 12) próbuje stworzyć wyłącznie pliku lub katalogu, który już istnieje. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NO_MODIFICATION_ALLOWED_ERR(code: 6) na próby wywołania removeRecursively w głównym systemie plików. -INVALID_MODIFICATION_ERR (kod: 9) jest generowany zamiast NOT_FOUND_ERR(code: 1) na trudny do katalogu moveTo, który nie istnieje.
+
+ [5]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+### Na bazie IndexedDB impl dziwactw (Firefox i IE)
+
+* `.` i `.` nie są obsługiwane.
+* IE obsługuje `file:///`-tryb; tylko obsługiwane tryb jest obsługiwany (http://localhost:xxxx).
+* Rozmiar plików Firefox nie jest ograniczona, ale każde rozszerzenie 50MB zwróci użytkownikowi uprawnienia. IE10 pozwala maksymalnie 10mb połączone "appcache" i IndexedDB używane w implementacji systemu plików bez monitowania, gdy trafisz na tym poziomie, które uzyskasz, jeśli chcesz mogła ona zostać zwiększony do max 250mb na stronie. Więc `rozmiar` parametru funkcja `requestFileSystem` nie wpływa na system plików Firefox i IE.
+* `readAsBinaryString` funkcja nie jest określona w specyfikacji i nie obsługiwane w IE i nie tylko.
+* `File.Type` ma zawsze wartość null.
+* Nie należy utworzyć wpis za pomocą DirectoryEntry wystąpienie wynik wywołania zwrotnego, który został usunięty. W przeciwnym razie dostaniesz wpisem"wiszące".
+* Zanim będzie można przeczytać plik, który został napisany tylko trzeba uzyskać nowe wystąpienie tego pliku.
+* Funkcja `setMetadata`, która nie jest określona w specyfikacji obsługuje tylko zmian pola `modificationTime`.
+* `copyTo` i `moveTo` funkcji nie obsługuje katalogi.
+* Metadanych w katalogów nie jest obsługiwana.
+* Zarówno Entry.remove i directoryEntry.removeRecursively nie usuwając niepuste katalogi - katalogi są usuwane są czyszczone z treści zamiast.
+* `abort` i `truncate` funkcje nie są obsługiwane.
+* zdarzenia postępu nie są zwalniani. Na przykład to obsługa będzie nie wykonywane:
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## Uaktualniania notatek
+
+W v1.0.0 tego pluginu struktury `FileEntry` i `DirectoryEntry` zmieniły się więcej zgodnie z opublikowaną specyfikacją.
+
+Poprzednie wersje (pre-1.0.0) plugin przechowywane urządzenia bezwzględna plik lokalizacja we właściwości `fullPath` `wpis` obiektów. Te ścieżki zazwyczaj będzie wyglądać
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Te ścieżki były także zwracany przez metodę `toURL()` `Entry` obiektów.
+
+Z v1.0.0 atrybut `fullPath` jest ścieżką do pliku, *względem katalogu głównego systemu plików HTML*. Tak powyżej ścieżki będzie teraz zarówno być reprezentowane przez obiekt `FileEntry` z `fullPath` o
+
+ /path/to/file
+
+
+Jeśli aplikacja działa z ścieżki bezwzględnej urządzeń, i możesz wcześniej źródło tych ścieżek przez właściwość `fullPath` `wpis` obiektów, należy zaktualizować kod, aby zamiast tego użyj `entry.toURL()`.
+
+Dla wstecznej kompatybilności, Metoda `resolveLocalFileSystemURL()` będzie zaakceptować urządzenia ścieżka bezwzględna i zwróci obiekt `Entry` odpowiadający, tak długo, jak ten plik istnieje w albo `TEMPORARY` lub `PERSISTENT` systemy plików.
+
+To szczególnie został problem z pluginem transferu plików, które poprzednio używane ścieżki bezwzględnej urządzeń (i wciąż można je przyjąć). Została zaktualizowana do pracy poprawnie z adresów URL plików, więc wymiana `entry.fullPath` z `entry.toURL()` powinno rozwiązać wszelkie problemy dostawanie ten plugin do pracy z plików w pamięci urządzenia.
+
+W v1.1.0 wartość zwracana przez `toURL()` został zmieniony (patrz \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) zwraca adres URL absolutnej "file://". wszędzie tam, gdzie jest to możliwe. Aby zapewnić ' cdvfile:'-URL można użyć `toInternalURL()` teraz. Ta metoda zwróci teraz adresy URL plików formularza
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+który służy do jednoznacznej identyfikacji pliku.
+
+## Wykaz kodów błędów i ich znaczenie
+
+Gdy błąd jest generowany, jeden z następujących kodów będzie służyć.
+
+| Kod | Stała |
+| ---:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Konfigurowanie wtyczka (opcjonalny)
+
+Zestaw dostępnych plików może być skonfigurowany na platformie. Zarówno iOS i Android Tag w `pliku config.xml`, których nazwy plików do instalacji. Domyślnie włączone są wszystkie korzenie systemu plików.
+
+
+
+
+
+### Android
+
+* `files`: katalogu przechowywania plików aplikacji
+* `files-external`: katalog aplikacji zewnętrznych plików
+* `sdcard`: katalog globalny plik zewnętrzny (to jest głównym karty SD, jeśli jedna jest zainstalowana). Musi mieć uprawnienia `android.permission.WRITE_EXTERNAL_STORAGE` wobec używać ten.
+* `cache`: katalogu wewnętrznej pamięci podręcznej aplikacji
+* `cache-external`: katalogu aplikacji zewnętrznych pamięci podręcznej
+* `root`: całe urządzenie systemu plików
+
+Android obsługuje również specjalnych plików o nazwie "dokumenty", który reprezentuje podkatalog "/ dokumenty /" w ramach systemu plików "pliki".
+
+### iOS
+
+* `library`: katalog biblioteki aplikacji
+* `documents`: dokumenty katalogu aplikacji
+* `cache`: katalogu pamięci podręcznej aplikacji
+* `bundle`: pakiet aplikacji; Lokalizacja aplikacji na dysku (tylko do odczytu)
+* `root`: całe urządzenie systemu plików
+
+Domyślnie katalogi biblioteki i dokumenty mogą być synchronizowane iCloud. Można również zażądać dwóch dodatkowych plików, `library-nosync` i `documents-nosync`, które stanowią specjalny katalog nie zsynchronizowane w `/Library` lub systemu plików `/Documents`.
diff --git a/plugins/cordova-plugin-file/doc/pl/plugins.md b/plugins/cordova-plugin-file/doc/pl/plugins.md
new file mode 100644
index 0000000..6e8fe86
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/pl/plugins.md
@@ -0,0 +1,101 @@
+
+
+# Uwagi dla programistów wtyczki
+
+Te notatki są przeznaczone przede wszystkim dla Androida i iOS deweloperów, którzy chcieli pisac pluginy które interfejs z systemu plików za pomocą wtyczki pliku.
+
+## Praca z Cordova pliku system adresów URL
+
+Od wersji 1.0.0, ten plugin ma używane adresy URL z `cdvfile` system dla wszystkich komunikacji przez most, a nie narażać urządzenia raw ścieżki systemu plików JavaScript.
+
+Na stronie JavaScript oznacza to, że FileEntry i DirectoryEntry obiekty mają fullPath atrybut, który jest głównym systemie plików HTML. Jeśli twój plugin JavaScript API akceptuje obiektu FileEntry lub DirectoryEntry, należy zadzwonić `.toURL()` dla tego obiektu przed przekazaniem Altpradl do kodu macierzystego.
+
+### Konwersja cdvfile: / / URL do ścieżki fileystem
+
+Wtyczek, które trzeba pisać do systemu plików może chcesz przekonwertować odebranych plików systemu adres URL lokalizacji rzeczywistych plików. Istnieje wiele sposobów robi to, w zależności od macierzystego platformy.
+
+Ważne jest, aby pamiętać, że nie wszystkie `cdvfile://` adresy URL są można zmapować na prawdziwe pliki w urządzeniu. Niektóre adresy URL może odnosić się do aktywów na urządzeniu, które nie są reprezentowane przez pliki, lub nawet może odnosić się do zasobów zdalnych. Ze względu na te możliwości wtyczki należy zawsze sprawdzić, czy się znaczącego wyniku powrót podczas próby konwersji adresów URL do ścieżki.
+
+#### Androida
+
+Na Android, najprostsza metoda konwersji `cdvfile://` URL do ścieżki systemu plików jest użycie `org.apache.cordova.CordovaResourceApi` . `CordovaResourceApi`jest kilka metod, które mogą obsługiwać `cdvfile://` adresów URL:
+
+ Widok sieci Web jest członkiem Plugin klasy CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ Uzyskać URL file:/// reprezentujących ten plik na urządzeniu / / lub ten sam adres URL niezmienione, jeśli nie mogą być mapowane do pliku fileURL Uri = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+Jest również możliwe, aby korzystać z wtyczki pliku bezpośrednio:
+
+ org.apache.cordova.file.FileUtils przywóz;
+ org.apache.cordova.file.FileSystem przywóz;
+ java.net.MalformedURLException przywóz;
+
+ Uzyskać pliku plugin manager wtyczki FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ Biorąc pod uwagę adres URL, uzyskać ścieżkę dla to spróbuj {String ścieżka = filePlugin.filesystemPathForURL(cdvfileURL);} catch (MalformedURLException e) {/ / url plików nie było uznane}
+
+
+Do przeliczenia ścieżki do `cdvfile://` URL:
+
+ org.apache.cordova.file.LocalFilesystemURL przywóz;
+
+ Uzyskanie obiektu LocalFilesystemURL na ścieżkę urządzenia / / lub null, jeśli nie może być reprezentowana jako adres URL cdvfile.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ Dostać reprezentację ciąg adresu URL obiektu String cdvfileURL = url.toString();
+
+
+Jeśli twój plugin tworzy plik, i chcesz zwraca obiekt FileEntry dla niego, użyj pliku plugin:
+
+ Zwraca JSON struktura nadaje się do powrotu do JavaScript, / / lub null, jeśli ten plik nie jest reprezentować jako adres URL cdvfile.
+ Wpis JSONObject = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+Cordova na iOS nie korzystać z tego samego `CordovaResourceApi` koncepcji jak Android. Na iOS należy użyć pliku plugin do konwersji między adresach URL i ścieżkach plików.
+
+ Uzyskać obiekt CDVFilesystem URL URL url ciąg CDVFilesystemURL * = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ Uzyskać ścieżkę dla URL obiektu, stawka zerowa, jeśli nie mogą być mapowane do ścieżki pliku NSString * = [filePlugin filesystemPathForURL:url];
+
+
+ Dostać CDVFilesystem URL obiektu na ścieżkę urządzenia lub / / zerowe, jeśli nie może być reprezentowana jako adres URL cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ Dostać reprezentację ciąg adresu URL obiektu NSString * cdvfileURL = [url absoluteString];
+
+
+Jeśli twój plugin tworzy plik, i chcesz zwraca obiekt FileEntry dla niego, użyj pliku plugin:
+
+ Dostać CDVFilesystem URL obiektu na ścieżkę urządzenia lub / / zerowe, jeśli nie może być reprezentowana jako adres URL cdvfile.
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ Struktura wrócić do JavaScript NSDictionary * wpis = [filePlugin makeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+W JavaScript, aby uzyskać `cdvfile://` adres URL z obiektu FileEntry lub DirectoryEntry, wystarczy zadzwonić `.toURL()` na to:
+
+ var cdvfileURL = entry.toURL();
+
+
+W plugin reakcji obsługi przerobić od zwróconych struktury FileEntry do rzeczywistego obiektu wejścia, kod obsługi należy zaimportować pliku plugin i utworzyć nowy obiekt:
+
+ utworzyć odpowiedni wpis obiektu var wpis;
+ Jeśli (entryStruct.isDirectory) {wpis = nowy DirectoryEntry (entryStruct.name, entryStruct.fullPath, nowe FileSystem(entryStruct.filesystemName));} jeszcze {wpis = nowy FileEntry (entryStruct.name, entryStruct.fullPath, nowe FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/plugins.md b/plugins/cordova-plugin-file/doc/plugins.md
new file mode 100644
index 0000000..a3329d6
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/plugins.md
@@ -0,0 +1,120 @@
+
+
+Notes for plugin developers
+===========================
+
+These notes are primarily intended for Android and iOS developers who want to write plugins which interface with the file system using the File plugin.
+
+Working with Cordova file system URLs
+-------------------------------------
+
+Since version 1.0.0, this plugin has used URLs with a `cdvfile` scheme for all communication over the bridge, rather than exposing raw device file system paths to JavaScript.
+
+On the JavaScript side, this means that FileEntry and DirectoryEntry objects have a fullPath attribute which is relative to the root of the HTML file system. If your plugin's JavaScript API accepts a FileEntry or DirectoryEntry object, you should call `.toURL()` on that object before passing it across the bridge to native code.
+
+### Converting cdvfile:// URLs to fileystem paths
+
+Plugins which need to write to the filesystem may want to convert a received file system URL to an actual filesystem location. There are multiple ways of doing this, depending on the native platform.
+
+It is important to remember that not all `cdvfile://` URLs are mappable to real files on the device. Some URLs can refer to assets on device which are not represented by files, or can even refer to remote resources. Because of these possibilities, plugins should always test whether they get a meaningful result back when trying to convert URLs to paths.
+
+#### Android
+
+On Android, the simplest method to convert a `cdvfile://` URL to a filesystem path is to use `org.apache.cordova.CordovaResourceApi`. `CordovaResourceApi` has several methods which can handle `cdvfile://` URLs:
+
+ // webView is a member of the Plugin class
+ CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ // Obtain a file:/// URL representing this file on the device,
+ // or the same URL unchanged if it cannot be mapped to a file
+ Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+It is also possible to use the File plugin directly:
+
+ import org.apache.cordova.file.FileUtils;
+ import org.apache.cordova.file.FileSystem;
+ import java.net.MalformedURLException;
+
+ // Get the File plugin from the plugin manager
+ FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ // Given a URL, get a path for it
+ try {
+ String path = filePlugin.filesystemPathForURL(cdvfileURL);
+ } catch (MalformedURLException e) {
+ // The filesystem url wasn't recognized
+ }
+
+To convert from a path to a `cdvfile://` URL:
+
+ import org.apache.cordova.file.LocalFilesystemURL;
+
+ // Get a LocalFilesystemURL object for a device path,
+ // or null if it cannot be represented as a cdvfile URL.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ // Get the string representation of the URL object
+ String cdvfileURL = url.toString();
+
+If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin:
+
+ // Return a JSON structure suitable for returning to JavaScript,
+ // or null if this file is not representable as a cdvfile URL.
+ JSONObject entry = filePlugin.getEntryForFile(file);
+
+#### iOS
+
+Cordova on iOS does not use the same `CordovaResourceApi` concept as Android. On iOS, you should use the File plugin to convert between URLs and filesystem paths.
+
+ // Get a CDVFilesystem URL object from a URL string
+ CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ // Get a path for the URL object, or nil if it cannot be mapped to a file
+ NSString* path = [filePlugin filesystemPathForURL:url];
+
+
+ // Get a CDVFilesystem URL object for a device path, or
+ // nil if it cannot be represented as a cdvfile URL.
+ CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
+ // Get the string representation of the URL object
+ NSString* cdvfileURL = [url absoluteString];
+
+If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin:
+
+ // Get a CDVFilesystem URL object for a device path, or
+ // nil if it cannot be represented as a cdvfile URL.
+ CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
+ // Get a structure to return to JavaScript
+ NSDictionary* entry = [filePlugin makeEntryForLocalURL:url]
+
+#### JavaScript
+
+In JavaScript, to get a `cdvfile://` URL from a FileEntry or DirectoryEntry object, simply call `.toURL()` on it:
+
+ var cdvfileURL = entry.toURL();
+
+In plugin response handlers, to convert from a returned FileEntry structure to an actual Entry object, your handler code should import the File plugin and create a new object:
+
+ // create appropriate Entry object
+ var entry;
+ if (entryStruct.isDirectory) {
+ entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
+ } else {
+ entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
+ }
+
diff --git a/plugins/cordova-plugin-file/doc/ru/index.md b/plugins/cordova-plugin-file/doc/ru/index.md
new file mode 100644
index 0000000..3c9fca9
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ru/index.md
@@ -0,0 +1,275 @@
+
+
+# cordova-plugin-file
+
+Этот плагин реализует API файла, позволяя доступ на чтение и запись в файлы, находящиеся на устройстве.
+
+Этот плагин основан на нескольких спецификации, в том числе: HTML5 API файла
+
+(Ныне несуществующей) каталоги и систему расширений Последнее: , хотя большая часть кода, плагин был написан, когда ранее спец был текущим:
+
+Он также реализует уничтожал spec:
+
+Для использования, пожалуйста, обратитесь к HTML5 скалы отличные [файловой системы статьи.][1]
+
+ [1]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+Обзор других вариантов хранения найти Cordova [хранения руководства][2].
+
+ [2]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+## Установка
+
+ cordova plugin add cordova-plugin-file
+
+
+## Поддерживаемые платформы
+
+* Amazon Fire OS
+* Android
+* BlackBerry 10
+* Firefox OS
+* iOS
+* Windows Phone 7 и 8 *
+* Windows 8 *
+
+* *Эти платформы не поддерживают `FileReader.readAsArrayBuffer` , ни `FileWriter.write(blob)` .*
+
+## Где хранить файлы
+
+По состоянию на v1.2.0 приведены URL-адреса для важных файлов в системные каталоги. Каждый URL-адрес в виде *file:///path/to/spot/*и может быть преобразован в `DirectoryEntry` с помощью`window.resolveLocalFileSystemURL()`.
+
+* `cordova.file.applicationDirectory`-Каталог только для чтения, где установлено приложение. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.applicationStorageDirectory`-Корневой каталог приложения в песочнице; на iOS это место только для чтения (но определенных подкаталогов [как `/Documents` ], чтения записи). Все данные, содержащиеся в частных в приложение. ( *iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.dataDirectory`-Хранения стойкие и частных данных в приложения в песочнице с использованием внутренней памяти (на Android, если необходимо использовать внешнюю память, использовать `.externalDataDirectory` ). На iOS, этот каталог не синхронизируется с iCloud (использование `.syncedDataDirectory` ). (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.cacheDirectory`-Каталог для кэшированных данных файлов или все файлы, которые ваше приложение может повторно создать легко. ОС может удалить эти файлы, когда устройства хватает на хранение, тем не менее, приложения не должны опираться на OS, чтобы удалить файлы здесь. (*iOS*, *Android*, *BlackBerry 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-Пространство приложения на внешнем хранилище. (*Android*)
+
+* `cordova.file.externalDataDirectory`-Куда положить файлы данных конкретного приложения на внешнем хранилище. (*Android*)
+
+* `cordova.file.externalCacheDirectory`-Применение кэш на внешние накопители. (*Android*)
+
+* `cordova.file.externalRootDirectory`-Корень внешние накопители (SD карта). (*Android*, *BlackBerry 10*)
+
+* `cordova.file.tempDirectory`-Временный каталог, что ОС можно снять на будет. Не следует полагаться на OS, чтобы очистить этот каталог; Ваше приложение всегда следует удалять файлы в соответствующих случаях. (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-Содержит файлы приложения, которые должны быть синхронизированы (например, к iCloud). (*iOS*)
+
+* `cordova.file.documentsDirectory`-Файлы для приложения, но это являются значимыми для других приложений (например, файлы Office). (*iOS*)
+
+* `cordova.file.sharedDirectory`-Файлы глобально доступной для всех приложений (*BlackBerry 10*)
+
+## Макеты файловой системы
+
+Хотя технически деталь реализации, она может быть очень полезно знать как `cordova.file.*` карта свойства физические пути на реальном устройстве.
+
+### iOS расположения файловой системы
+
+| Путь к устройству | `Cordova.File.*` | `iosExtraFileSystems` | r/w? | стойкие? | Очищает ОС | Синхронизация | частные |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:----:|:--------:|:----------:|:-------------:|:-------:|
+| `/ var/мобильного/применения/< UUID > /` | applicationStorageDirectory | - | r | Н/Д | Н/Д | Н/Д | Да |
+| `appname.app/` | applicationDirectory | расслоение | r | Н/Д | Н/Д | Н/Д | Да |
+| `www/` | - | - | r | Н/Д | Н/Д | Н/Д | Да |
+| `Documents/` | documentsDirectory | документы | r/w | Да | Нет | Да | Да |
+| `NoCloud/` | - | документы nosync | r/w | Да | Нет | Нет | Да |
+| `Library` | - | Библиотека | r/w | Да | Нет | Да? | Да |
+| `NoCloud/` | dataDirectory | Библиотека nosync | r/w | Да | Нет | Нет | Да |
+| `Cloud/` | syncedDataDirectory | - | r/w | Да | Нет | Да | Да |
+| `Caches/` | cacheDirectory | кэш | r/w | Да * | Да * * *| | Нет | Да |
+| `tmp/` | tempDirectory | - | r/w | Не * * | Да * * *| | Нет | Да |
+
+* Файлы сохраняются приложения перезагрузки и обновления, но этот каталог может быть очищен, когда ОС желаний. Ваше приложение должно иметь возможность воссоздать любое содержание, которое может быть удалено.
+
+* * Файлы могут сохраняться перезагрузками app, но не полагайтесь на это поведение. Для продолжения обновления файлов не гарантируется. Приложение должно удалить файлы из этого каталога, когда это применимо, как операционная система не гарантирует когда (или даже если) эти файлы будут удалены.
+
+* * *| ОС может очистить содержимое этого каталога, когда он считает это необходимым, но не полагайтесь на это. Необходимо снять этот каталог в зависимости от вашего приложения.
+
+### Расположения Android файловой системы
+
+| Путь к устройству | `Cordova.File.*` | `AndroidExtraFileSystems` | r/w? | стойкие? | Очищает ОС | частные |
+|:--------------------------------- |:----------------------------------- |:------------------------- |:----:|:--------:|:----------:|:-------:|
+| `File:///android_asset/` | applicationDirectory | | r | Н/Д | Н/Д | Да |
+| `/ Data/data/< app-id > /` | applicationStorageDirectory | - | r/w | Н/Д | Н/Д | Да |
+| `cache` | cacheDirectory | кэш | r/w | Да | Да * | Да |
+| `files` | dataDirectory | файлы | r/w | Да | Нет | Да |
+| `Documents` | | документы | r/w | Да | Нет | Да |
+| `< sdcard > /` | externalRootDirectory | SDCard | r/w | Да | Нет | Нет |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | Да | Нет | Нет |
+| `cache` | externalCacheDirectry | кэш внешние | r/w | Да | Не * * | Нет |
+| `files` | externalDataDirectory | файлы внешние | r/w | Да | Нет | Нет |
+
+* ОС может периодически удалять этот каталог, но не полагайтесь на это поведение. Очистите содержимое этого каталога в зависимости от вашего приложения. Если пользователь вручную очистить кэш, содержимое этого каталога будут удалены.
+
+* * ОС не ясно этот каталог автоматически; Вы несете ответственность за управление содержимым самостоятельно. Если пользователь вручную очистить кэш, содержимое каталога будут удалены.
+
+**Примечание**: Если нельзя монтировать внешние накопители, `cordova.file.external*` Свойства`null`.
+
+### BlackBerry 10 расположения файловой системы
+
+| Путь к устройству | `Cordova.File.*` | r/w? | стойкие? | Очищает ОС | частные |
+|:--------------------------------------------------- |:--------------------------- |:----:|:--------:|:----------:|:-------:|
+| `File:///Accounts/1000/AppData/ < app id > /` | applicationStorageDirectory | r | Н/Д | Н/Д | Да |
+| `app/native` | applicationDirectory | r | Н/Д | Н/Д | Да |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | Нет | Да | Да |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Да | Нет | Да |
+| `File:///Accounts/1000/Removable/SDCard` | externalRemovableDirectory | r/w | Да | Нет | Нет |
+| `File:///Accounts/1000/Shared` | sharedDirectory | r/w | Да | Нет | Нет |
+
+*Примечание*: при развертывании приложения для работы периметра, все пути относительны /accounts/1000-enterprise.
+
+## Особенности Android
+
+### Местоположение Android постоянного хранения
+
+Есть несколько допустимых мест для хранения постоянных файлов на устройстве Android. Смотрите [эту страницу][3] для широкого обсуждения различных возможностей.
+
+ [3]: http://developer.android.com/guide/topics/data/data-storage.html
+
+Предыдущие версии плагина будет выбирать расположение временных и постоянных файлов при запуске, основанный на ли устройство утверждал, что SD-карта (или эквивалентные хранения раздел) был смонтирован. Если была смонтирована SD-карты, или если большой внутренней памяти раздел был доступен (такие как на устройствах Nexus,), то постоянные файлы будут храниться в корне этого пространства. Это означало, что все apps Cordova могли видеть все файлы, имеющиеся на карте.
+
+Если SD-карты не был доступен, то предыдущих версий будет хранить данные в `/data/data/` , которая изолирует приложения друг от друга, но все еще может причина данные распределяются между пользователями.
+
+Это теперь можно выбрать, следует ли хранить файлы в месте хранения внутренних файлов, или с использованием предыдущей логики, с предпочтением в вашем приложении `config.xml` файл. Чтобы сделать это, добавить один из этих двух линий в `config.xml` :
+
+
+
+
+
+
+Без этой линии, будет использовать файл плагина `Compatibility` по умолчанию. Если тег предпочтений присутствует и не является одним из этих значений, приложение не запустится.
+
+Если ранее была отгружена приложения для пользователей, используя старые (до 1.0) версию этого плагина и имеет сохраненные файлы в файловой системе постоянных, то вы должны установить предпочтения `Compatibility` . Переключение местоположение для «Внутреннего» будет означать, что существующие пользователи, которые обновить их применение может быть не в состоянии получить доступ к их сохраненные ранее файлы, в зависимости от их устройства.
+
+Если ваше приложение является новым или ранее никогда не хранит файлы в стойких файловой системы, то `Internal` как правило рекомендуется настройка.
+
+## Особенности iOS
+
+* `cordova.file.applicationStorageDirectory`доступен только для чтения; попытка хранения файлов в корневом каталоге не удастся. Использовать один из других `cordova.file.*` свойства, определенные для iOS (только `applicationDirectory` и `applicationStorageDirectory` доступны только для чтения).
+* `FileReader.readAsText(blob, encoding)`
+ * `encoding`Параметр не поддерживается, и UTF-8 кодирование действует всегда.
+
+### iOS место постоянного хранения
+
+Существует два допустимых местоположений для хранения постоянных файлов на устройства iOS: документы каталогов и библиотека. Предыдущие версии плагина только когда-либо постоянные файлы хранятся в папке документы. Это был побочный эффект делает все файлы приложения в iTunes, который часто был непреднамеренным, особенно для приложений, которые обрабатывают большое количество мелких файлов, вместо того, чтобы производить полный комплект документов для экспорта, который является цель каталога.
+
+Это теперь можно выбрать, следует ли хранить файлы в документы или каталоге библиотеки, с предпочтением в вашем приложении `config.xml` файл. Чтобы сделать это, добавить один из этих двух линий в `config.xml` :
+
+
+
+
+
+
+Без этой линии, будет использовать файл плагина `Compatibility` по умолчанию. Если тег предпочтений присутствует и не является одним из этих значений, приложение не запустится.
+
+Если ранее была отгружена приложения для пользователей, используя старые (до 1.0) версию этого плагина и имеет сохраненные файлы в файловой системе постоянных, то вы должны установить предпочтения `Compatibility` . Переключение расположения `Library` будет означать, что существующих пользователей обновить их применения будет не в состоянии получить доступ к их сохраненные ранее файлы.
+
+Если ваше приложение является новым или ранее никогда не хранит файлы в стойких файловой системы, то `Library` как правило рекомендуется настройка.
+
+## Особенности Firefox OS
+
+API файловой системы изначально не поддерживается Firefox OS и реализуется как оболочка поверх indexedDB.
+
+* Не вынимая непустые каталоги
+* Не поддерживает метаданные для каталогов
+* Методы `copyTo` и `moveTo` не поддерживает каталоги
+
+Поддерживаются следующие пути данных: * `applicationDirectory` -использует `xhr` чтобы получить локальные файлы, которые упакованы с приложением. * `dataDirectory` - Для постоянных данных конкретного приложения файлов. * `cacheDirectory` -Кэшированных файлов, которые должны выжить перезагрузки приложения (Apps не следует полагаться на OS, чтобы удалить файлы из здесь).
+
+## Обновление примечания
+
+В v1.0.0 этого плагина `FileEntry` и `DirectoryEntry` структур изменились, более соответствует опубликованной спецификации.
+
+Предыдущий (pre-1.0.0) версии плагина хранятся устройства Абсолют файл расположение в `fullPath` свойства `Entry` объектов. Эти пути обычно будет выглядеть
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+Эти пути также были возвращены `toURL()` метода `Entry` объектов.
+
+С v1.0.0 `fullPath` атрибут является путь к файлу, *заданный относительно корня файловой системы HTML*. Таким образом, выше пути будет теперь оба быть представлено `FileEntry` объект с `fullPath` из
+
+ /path/to/file
+
+
+Если ваше приложение работает с устройства Абсолют путями, и ранее были получены эти пути через `fullPath` свойства `Entry` объектов, то вам следует обновить код для использования `entry.toURL()` вместо этого.
+
+Для обратной совместимости, `resolveLocalFileSystemURL()` метод будет принимать путь Абсолют устройства и будет возвращать `Entry` объект, соответствующий его, до тех пор, как этот файл существует в рамках либо `TEMPORARY` или `PERSISTENT` файловых систем.
+
+Это особенно была проблема с плагином передачи файлов, который ранее использовался устройства Абсолют пути (и все еще может принять их). Он был обновлен для корректной работы с файловой системы URL, так что замена `entry.fullPath` с `entry.toURL()` должен решить любые вопросы, получить этот плагин для работы с файлами на устройстве.
+
+В v1.1.0 возвращаемое значение из `toURL()` был изменен (см. \[CB-6394\] (https://issues.apache.org/jira/browse/CB-6394)) для возвращения URL-адрес абсолютным «file://». где это возможно. Для обеспечения ' cdvfile:'-вы можете использовать URL-адрес `toInternalURL()` сейчас. Этот метод будет возвращать теперь файловой системы URL формы
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+который может использоваться для уникальной идентификации файла.
+
+## Список кодов ошибок и значения
+
+Когда возникает ошибка, один из следующих кодов будет использоваться.
+
+| Код | Постоянная |
+| ---:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## Настройка плагина (опционально)
+
+Набор доступных файловых систем может быть настроен на платформе. IOS и Android признают тег в `config.xml` имена которых файловые системы для установки. По умолчанию включены все корни файловой системы.
+
+
+
+
+
+### Android
+
+* `files`: Каталог для хранения внутреннего файла приложения
+* `files-external`: Каталог хранения внешнего файла приложения
+* `sdcard`: Глобальный внешний файл каталог хранения (это корень SD-карты, если таковая установлена). Вы должны иметь `android.permission.WRITE_EXTERNAL_STORAGE` разрешение использовать это.
+* `cache`: Каталог внутреннего кэша приложения
+* `cache-external`: Каталог приложения внешней кэш-памяти
+* `root`: Все устройство файловой системы
+
+Android поддерживает также Специальный файловую систему под названием «документы», которая представляет подкаталог «/ документы /» в пределах файловой системы «файлы».
+
+### iOS
+
+* `library`: Каталог библиотеки приложения
+* `documents`: Каталог документов приложения
+* `cache`: Каталог кэша приложения
+* `bundle`: Пакет приложения; расположение самого приложения на диске (только для чтения)
+* `root`: Все устройство файловой системы
+
+По умолчанию каталоги библиотеки и документы можно синхронизировать с iCloud. Вы также можете заказать два дополнительных файловых систем, `library-nosync` и `documents-nosync` , которые представляют Специальный каталог не синхронизируются в `/Library` или `/Documents` файловой системы.
diff --git a/plugins/cordova-plugin-file/doc/ru/plugins.md b/plugins/cordova-plugin-file/doc/ru/plugins.md
new file mode 100644
index 0000000..2445d09
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/ru/plugins.md
@@ -0,0 +1,124 @@
+
+
+# Примечания для разработчиков плагинов
+
+Эти примечания предназначены прежде всего для Android и iOS разработчиков, которые хотят писать плагины какой интерфейс с файловой системой, с помощью файла плагина.
+
+## Работа с Кордова файловой системы URL
+
+Начиная с версии 1.0.0, этот плагин использует URL-адресов с `cdvfile` схема для всех коммуникации через мост, а не подвергая пути файловой системы raw устройства для JavaScript.
+
+На стороне JavaScript это означает, что объекты DirectoryEntry и FileEntry fullPath атрибут, который является по отношению к корневой файловой системе HTML. Если ваш плагин JavaScript API принимает объект DirectoryEntry или FileEntry, необходимо вызвать `.toURL()` для этого объекта перед передачей их через мост в машинный код.
+
+### Преобразование cdvfile: / / URL-адреса в пути fileystem
+
+Плагины, которые нужно написать в файловой системе может потребоваться преобразовать URL-адреса системы полученный файл в место фактической файловой системы. Существует несколько способов сделать это, в зависимости от родной платформе.
+
+Важно помнить, что не все `cdvfile://` URL-адреса являются отображаемыми файлами на устройстве. Некоторые URL может относиться к активам на устройстве, которые не представлены файлы, или может даже обратиться к удаленным ресурсам. Из-за эти возможности плагины следует всегда проверять ли они получают результат обратно при попытке преобразовать URL-адреса в пути.
+
+#### Android
+
+На Android, самый простой способ для преобразования `cdvfile://` URL-адрес к пути файловой системы заключается в использовании `cordova-plugin-CordovaResourceApi` . `CordovaResourceApi`Есть несколько методов, которые можно обработать `cdvfile://` URL-адреса:
+
+ // webView is a member of the Plugin class
+ CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ // Obtain a file:/// URL representing this file on the device,
+ // or the same URL unchanged if it cannot be mapped to a file
+ Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+Это также можно использовать плагин файл непосредственно:
+
+ import cordova-plugin-file.FileUtils;
+ import cordova-plugin-file.FileSystem;
+ import java.net.MalformedURLException;
+
+ // Get the File plugin from the plugin manager
+ FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ // Given a URL, get a path for it
+ try {
+ String path = filePlugin.filesystemPathForURL(cdvfileURL);
+ } catch (MalformedURLException e) {
+ // The filesystem url wasn't recognized
+ }
+
+
+Для преобразования пути к `cdvfile://` URL-адрес:
+
+ import cordova-plugin-file.LocalFilesystemURL;
+
+ // Get a LocalFilesystemURL object for a device path,
+ // or null if it cannot be represented as a cdvfile URL.
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ // Get the string representation of the URL object
+ String cdvfileURL = url.toString();
+
+
+Если ваш плагин создает файл, и вы хотите вернуть объект FileEntry для него, используйте файл плагина:
+
+ // Return a JSON structure suitable for returning to JavaScript,
+ // or null if this file is not representable as a cdvfile URL.
+ JSONObject entry = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+Кордова на iOS не использовать те же `CordovaResourceApi` понятие, как Android. На iOS вы должны использовать файл плагин для преобразования URL-адреса и пути файловой системы.
+
+ // Get a CDVFilesystem URL object from a URL string
+ CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ // Get a path for the URL object, or nil if it cannot be mapped to a file
+ NSString* path = [filePlugin filesystemPathForURL:url];
+
+
+ // Get a CDVFilesystem URL object for a device path, or
+ // nil if it cannot be represented as a cdvfile URL.
+ CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
+ // Get the string representation of the URL object
+ NSString* cdvfileURL = [url absoluteString];
+
+
+Если ваш плагин создает файл, и вы хотите вернуть объект FileEntry для него, используйте файл плагина:
+
+ // Get a CDVFilesystem URL object for a device path, or
+ // nil if it cannot be represented as a cdvfile URL.
+ CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
+ // Get a structure to return to JavaScript
+ NSDictionary* entry = [filePlugin makeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+В JavaScript, чтобы получить `cdvfile://` URL от объекта DirectoryEntry или FileEntry, просто позвоните `.toURL()` на него:
+
+ var cdvfileURL = entry.toURL();
+
+
+В плагин обработчики ответ для преобразования из возвращаемой структуры FileEntry объект фактического вступления, код обработчика следует импортировать файл плагина и создайте новый объект:
+
+ // create appropriate Entry object
+ var entry;
+ if (entryStruct.isDirectory) {
+ entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
+ } else {
+ entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
+ }
diff --git a/plugins/cordova-plugin-file/doc/zh/README.md b/plugins/cordova-plugin-file/doc/zh/README.md
new file mode 100644
index 0000000..c600587
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/zh/README.md
@@ -0,0 +1,335 @@
+
+
+# cordova-plugin-file
+
+[](https://travis-ci.org/apache/cordova-plugin-file)
+
+這個外掛程式實現檔 API 允許對檔駐留在該設備上的讀/寫訪問。
+
+這個外掛程式基於幾個規格,包括: HTML5 檔 API [HTTP://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/)
+
+(現已解散) 目錄和系統擴展最新: [HTTP://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)雖然大部分的外掛程式代碼寫時較早的規格是當前: [HTTP://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/)
+
+它還實現 FileWriter 規格: [HTTP://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html)
+
+用法,請參閱對 HTML5 的岩石優秀[檔案系統文章。](http://www.html5rocks.com/en/tutorials/file/filesystem/)
+
+其他存儲選項的概述,請參閱科爾多瓦的[存儲指南](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
+
+這個外掛程式定義全球 `cordova.file` 物件。
+
+雖然在全球範圍內,它不可用直到 `deviceready` 事件之後。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## 安裝
+
+ cordova plugin add cordova-plugin-file
+
+
+## 支援的平臺
+
+ * 亞馬遜火 OS
+ * Android 系統
+ * 黑莓 10
+ * 火狐瀏覽器作業系統
+ * iOS
+ * Windows Phone 7 和 8 *
+ * Windows 8 *
+ * Windows*
+ * 瀏覽器
+
+\* *These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`.*
+
+## 存儲檔的位置
+
+截至 v1.2.0,提供重要的檔案系統目錄的 Url。 每個 URL 位於表單 *file:///path/to/spot/*,和可以轉換為使用 `window.resolveLocalFileSystemURL()` 的 `DirectoryEntry`.
+
+ * `cordova.file.applicationDirectory`-唯讀目錄在哪裡安裝的應用程式。(*iOS*、*安卓*、*黑莓 10*)
+
+ * `cordova.file.applicationStorageDirectory`-根目錄下的應用程式的沙箱 ;在 iOS 上此位置是唯讀 (但特定的子目錄 [像 `/Documents` ] 都是讀寫)。 中包含的所有資料都是私有的應用程式。 ( *iOS*、*安卓*、*黑莓 10*)
+
+ * `cordova.file.dataDirectory`資料持久性和私有資料存儲在內部記憶體使用的應用程式的沙箱內 (在安卓系統,如果你需要使用外部儲存體,使用 `.externalDataDirectory` )。 在 iOS,此目錄不與 iCloud 同步 (使用 `.syncedDataDirectory` )。 (*iOS*、*安卓*、*黑莓 10*)
+
+ * `cordova.file.cacheDirectory`-緩存的資料檔案或您的應用程式重新可以輕鬆地創建的任何檔的目錄。 作業系統可能會刪除這些檔,該設備在存儲上運行低時,然而,應用程式不應依賴的作業系統,請刪除檔在這裡。 (*iOS*、*安卓*、*黑莓 10*)
+
+ * `cordova.file.externalApplicationStorageDirectory`-應用程式外部存儲上的空間。(*安卓*)
+
+ * `cordova.file.externalDataDirectory`-放在外部存儲特定于應用程式的資料檔案的位置。(*安卓*)
+
+ * `cordova.file.externalCacheDirectory`-在外部存儲應用程式緩存。(*安卓*)
+
+ * `cordova.file.externalRootDirectory`-外部存儲 (SD 卡) 的根。(*安卓*、*黑莓 10*)
+
+ * `cordova.file.tempDirectory`-OS 可以清除時的空目錄會。 不依賴于 OS,以清除此目錄 ;您的應用程式,應總是移除作為適用的檔。 (*iOS*)
+
+ * `cordova.file.syncedDataDirectory`-保存應同步 (例如到 iCloud) 的特定于應用程式的檔。(*iOS*)
+
+ * `cordova.file.documentsDirectory`-檔私有的應用程式,但這是對其他應用程式 (例如 Office 檔) 有意義。(*iOS*)
+
+ * `cordova.file.sharedDirectory`-對所有應用程式 (*黑莓 10*全域可用的檔)
+
+## 檔案系統佈局
+
+雖然技術上實現的細節,它可以是很有必要瞭解如何 `cordova.file.*` 屬性對應到實體路徑在實際設備上。
+
+### iOS 檔案系統佈局
+
+| 設備路徑 | `cordova.file.*` | `iosExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 同步 | 私人 |
+|:---------------------------------------------- |:--------------------------- |:--------------------- |:------:|:-------:|:------------:|:---:|:--:|
+| `/ 無功/移動/應用程式/< UUID > /` | applicationStorageDirectory | - | r | 不適用 | 不適用 | 不適用 | 是啊 |
+| `appname.app/` | applicationDirectory | 束 | r | 不適用 | 不適用 | 不適用 | 是啊 |
+| `www/` | - | - | r | 不適用 | 不適用 | 不適用 | 是啊 |
+| `Documents/` | documentsDirectory | 檔 | r/w | 是啊 | 無 | 是啊 | 是啊 |
+| `NoCloud/` | - | 檔 nosync | r/w | 是啊 | 無 | 無 | 是啊 |
+| `Library` | - | 圖書館 | r/w | 是啊 | 無 | 是嗎? | 是啊 |
+| `NoCloud/` | dataDirectory | 圖書館 nosync | r/w | 是啊 | 無 | 無 | 是啊 |
+| `Cloud/` | syncedDataDirectory | - | r/w | 是啊 | 無 | 是啊 | 是啊 |
+| `Caches/` | cacheDirectory | 快取記憶體 | r/w | 是啊 * | 是啊**\* | 無 | 是啊 |
+| `tmp/` | tempDirectory | - | r/w | 無** | 是啊**\* | 無 | 是啊 |
+
+\ * 檔堅持跨應用程式重新開機和升級,但每當 OS 的欲望,可以清除此目錄。您的應用程式應該能夠重新創建任何內容可能會被刪除。
+
+**檔可能會持續整個應用程式重新開機,但不是依賴于這種行為。 不保證檔在更新之間持續存在。 您的應用程式時適用,是應該刪除此目錄的檔,因為作業系統並不能保證何時 (或即使) 中刪除這些檔。
+
+**\ * 作業系統可能會清除此目錄的內容,每當它感覺它是必要的但做不依賴于此。 你應該清除此目錄為適合您的應用程式。
+
+### Android 的檔案系統佈局
+
+| 設備路徑 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 |
+|:------------------------------------------------ |:----------------------------------- |:------------------------- |:------:|:-----:|:-------:|:--:|
+| `file:///android_asset/` | applicationDirectory | | r | 不適用 | 不適用 | 是啊 |
+| `/ 資料資料/< 應用程式 id > /` | applicationStorageDirectory | - | r/w | 不適用 | 不適用 | 是啊 |
+| `cache` | cacheDirectory | 快取記憶體 | r/w | 是啊 | 是啊\* | 是啊 |
+| `files` | dataDirectory | 檔 | r/w | 是啊 | 無 | 是啊 |
+| `Documents` | | 檔 | r/w | 是啊 | 無 | 是啊 |
+| `< sd 卡 > /` | externalRootDirectory | sd 卡 | r/w | 是啊 | 無 | 無 |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | 是啊 | 無 | 無 |
+| `cache` | externalCacheDirectry | 外部快取記憶體 | r/w | 是啊 | 無** | 無 |
+| `files` | externalDataDirectory | 外部檔 | r/w | 是啊 | 無 | 無 |
+
+\ * 作業系統可能定期清除此目錄,但不是依賴于這種行為。 清除此為適合您的應用程式的目錄的內容。 使用者應手動清除緩存,將刪除此目錄的內容。
+
+** OS 不會清除此目錄自動;你是負責管理自己的內容。 使用者應手動清除緩存,目錄中的內容將被刪除。
+
+**注**: 如果外部存儲無法裝入,`cordova.file.external*` 屬性為 `空`.
+
+### 黑莓 10 檔案系統佈局
+
+| 設備路徑 | `cordova.file.*` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 |
+|:----------------------------------------------------------- |:--------------------------- |:------:|:-----:|:-----:|:--:|
+| `file:///accounts/1000/appdata/ < 應用程式 id > /` | applicationStorageDirectory | r | 不適用 | 不適用 | 是啊 |
+| `app/native` | applicationDirectory | r | 不適用 | 不適用 | 是啊 |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 無 | 是啊 | 是啊 |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 是啊 | 無 | 是啊 |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 是啊 | 無 | 無 |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | 是啊 | 無 | 無 |
+
+*注意*: 當應用程式部署工作週邊時,所有路徑都是相對於 /accounts/1000-enterprise。
+
+## Android 的怪癖
+
+### Android 的持久性存儲位置
+
+有很多有效的位置來存儲持久性檔在 Android 設備上。 請參閱 [此頁面](http://developer.android.com/guide/topics/data/data-storage.html) 的各種可能性進行廣泛討論。
+
+以前版本的外掛程式會選擇在啟動時,基於該設備是否聲稱 SD 卡 (或等效存儲分區) 展開,臨時和永久檔的位置。 如果被掛載 SD 卡,或一個大的內部存儲分區可用 (如 nexus 系列設備上) 然後持久性檔將存儲在該空間的根目錄中。 這意味著所有的科爾多瓦應用程式可以看到所有可用的檔在卡片上。
+
+如果 SD 卡不是可用的那麼以前的版本中將存儲資料下的 `/data/data/`,其中隔離應用程式從彼此,但仍可能導致使用者之間共用的資料。
+
+現在可以選擇是否將檔存儲在內部檔的存儲位置,或使用以前的邏輯,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`:
+
+
+
+
+
+
+如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。
+
+如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到"Internal"的位置,將意味著現有使用者升級他們的應用程式可能無法訪問他們以前存儲的檔,具體取決於他們的設備。
+
+如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。
+
+### 緩慢的遞迴操作為 /android_asset 的
+
+上市資產目錄是在 android 系統很慢的。 你可以讓時間加速了不過,通過將`src/android/build-extras.gradle`添加到您的 android 專案的根 (也需要 cordova-android@4.0.0 或更高版本)。
+
+## iOS 的怪癖
+
+ * `cordova.file.applicationStorageDirectory`是唯讀的 ;試圖存儲內的根目錄中的檔將會失敗。 使用的另一個 `cordova.file.*` 為 iOS 定義的屬性 (只有 `applicationDirectory` 和 `applicationStorageDirectory` 都是唯讀)。
+ * `FileReader.readAsText(blob, encoding)`
+ * `encoding`參數不受支援,而 utf-8 編碼總是效果。
+
+### iOS 的持久性存儲位置
+
+有兩個有效的位置來存儲持久性在 iOS 設備上的檔: 檔目錄和圖書館目錄。 以前版本的外掛程式永遠只能將持久性檔存儲在文檔目錄中。 這已經使所有應用程式檔可見在 iTunes,往往是無意為之,尤其是對於處理大量小檔的應用程式中,而不是生產供出口,該目錄的既定的目標是證件齊全的副作用。
+
+現在可以選擇是否將檔存儲在檔或庫目錄,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`:
+
+
+
+
+
+
+如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。
+
+如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到 `Library` 的位置,將意味著現有使用者升級他們的應用程式將無法訪問他們以前存儲的檔。
+
+如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。
+
+## 火狐瀏覽器作業系統的怪癖
+
+檔案系統 API 本身不支援火狐瀏覽器的作業系統,作為墊片在 indexedDB 上實現的。
+
+ * 不會失敗時刪除非空的目錄
+ * 不支援中繼資料的目錄
+ * 方法 `copyTo` 和 `moveTo` 不支援目錄
+
+支援以下資料路徑: * `applicationDirectory`-使用 `xhr` 獲取與應用程式打包的本地檔。 `dataDirectory`-用於持久性的特定于應用程式的資料檔案。 `cacheDirectory`-生存應重新開機應用程式的快取檔案 (應用程式不應依賴作業系統來刪除檔在這裡)。
+
+## 瀏覽器的怪癖
+
+### 常見的怪癖和備註
+
+ * 每個瀏覽器使用其自己的沙箱檔案系統。IE 和火狐瀏覽器使用 IndexedDB 作為一個基地。所有瀏覽器都使用正斜杠作為路徑中的目錄分隔符號。
+ * 目錄條目不得不先後創建。 例如,調用 `fs.root.getDirectory (' dir1/dir2 ',{create:true},successCallback,errorCallback)`,如果不存在 dir1 將失敗。
+ * 外掛程式將請求使用者許可權,以便在應用程式初次開機使用持久性存儲。
+ * 外掛程式支援 `cdvfile://localhost` (本地資源) 只。通過 `cdvfile` 不支援外部資源即.
+ * 該外掛程式不遵循 ["檔案系統 API 8.3 命名限制"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
+ * Blob 和檔 ' `close` 功能不受支援。
+ * `FileSaver` 和 `BlobBuilder` 不支援這個外掛程式,沒有存根 (stub)。
+ * 該外掛程式不支援 `requestAllFileSystems`。這個功能也是缺少規範中。
+ * 在目錄中的條目將不會被刪除,如果您使用 `create: true` 標誌為現有目錄。
+ * 不支援通過建構函式創建的檔。你應該使用 entry.file 方法。
+ * 每個瀏覽器使用它自己的形式為 blob 的 URL 引用。
+ * 支援 `readAsDataURL` 功能,但在 Chrome 中的媒體類型取決於輸入副檔名,在 IE 中的媒體類型都始終空著 (這是 `純文字` 按照說明書一樣),在 Firefox 中的媒體類型始終是 `應用程式/八位位元組流`。 例如,如果內容是 `abcdefg` 然後火狐瀏覽器返回 `資料: 應用程式 / 八位位元組流 ; base64,YWJjZGVmZw = =`,即返回 `資料: ; base64,YWJjZGVmZw = =`,鉻返回 `資料: < 媒體類型根據擴展條目名稱 > ; base64,YWJjZGVmZw = =`.
+ * 在表單 `file:///persistent/path/to/entry` 火狐瀏覽器 IE),`toInternalURL` 返回的路徑。 鉻在表單 `cdvfile://localhost/persistent/file` 返回的路徑.
+
+### 鉻的怪癖
+
+ * 設備準備好事件之後,chrome 檔案系統並不能立即準備。作為一種變通方法,您可以訂閱到 `filePluginIsReady` 事件。示例:
+
+```javascript
+window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+```
+
+你可以使用 `window.isFilePluginReadyRaised` 函數來檢查是否已經引發了事件。 -window.requestFileSystem 臨時和永久性檔案系統配額並不局限于鉻。 為增加中鉻的持久性存儲,您需要調用 `window.initPersistentFileSystem` 方法。 預設情況下,持久性存儲配額為 5 MB。 鉻需要 `— — 允許--訪問-從-檔` 通過 `file:///` 協定運行參數對 API 的支援。 -如果您使用標誌,將不更改 `檔` 物件 `{create:true}` 現有 `條目` 的時候。 -事件 `可取消` 屬性設置為 true 在 Chrome 中。 這是違反了 [規範](http://dev.w3.org/2009/dap/file-system/file-writer.html)。 -中鉻的 `toURL` 函數返回 `檔案系統:`-首碼路徑具體取決於應用程式主機。 例如,`filesystem:file:///persistent/somefile.txt`,`filesystem:HTTP://localhost:8080/persistent/somefile.txt`。 -`toURL` 函數結果不包含尾部反斜線在目錄條目的情況下。 鉻雖然正確解析目錄帶斜杠落後的 url。 -`resolveLocalFileSystemURL` 方法需要入站的 `url` 必須具有 `檔案系統` 首碼。 例如,`resolveLocalFileSystemURL` 的 `url` 參數應在表單 `filesystem:file:///persistent/somefile.txt` 而不是表單 `file:///persistent/somefile.txt` 在安卓系統。 -不推薦使用 `toNativeURL` 函數不受支援,並且沒有存根 (stub)。 -`setMetadata` 功能是沒有說出的規格,並且不支援。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 SYNTAX_ERR(code: 8) 上請求一個不存在的檔案系統。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 PATH_EXISTS_ERR(code: 12) 上嘗試專門創建一個檔或目錄,它已經存在。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NO_MODIFICATION_ALLOWED_ERR(code: 6) 在試圖調用 removeRecursively 的根檔案系統上。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NOT_FOUND_ERR(code: 1) 試到 moveTo 目錄不存在。
+
+### 基於 IndexedDB 的 impl 怪癖 (Firefox 和 IE)
+
+ * `.` 和 `.` 不受支援。
+ * IE 不支援 `file:///`-模式 ;只有託管的模式是支援 (HTTP://localhost:xxxx)。
+ * 火狐瀏覽器的檔案系統大小不是有限,但每個 50 MB 擴展會要求使用者的許可權。 IE10 允許達 10 mb 的 AppCache 和 IndexedDB 檔案系統的實現中使用而不會提示,一旦你達到這一水準你會詢問您是否允許它增加到每個網站的 250 mb 的最大合併。 所以 `requestFileSystem` 函數的 `大小` 參數並不影響檔案系統相容 Firefox 和 IE。
+ * `readAsBinaryString` 函數在規範中沒有注明不支援在 IE 中和沒有存根 (stub)。
+ * `file.type` 始終為 null。
+ * 您不應創建條目使用已刪除的目錄實例回檔結果。否則,你會得到一個 '掛條目'。
+ * 您可以讀取一個檔,其中只是寫之前你需要獲得的此檔的新實例。
+ * `setMetadata` 函數,在規範中沒有注明支援 `modificationTime` 欄位的更改。
+ * `copyTo` 和 `moveTo` 函數不支援目錄。
+ * 不支援目錄的中繼資料。
+ * 兩個 Entry.remove 和 directoryEntry.removeRecursively 不失敗時刪除非空的目錄-相反與內容一起清理目錄被刪除。
+ * 不支援 `abort` 和 `truncate` 函數。
+ * 進度事件不會觸發。例如,將不執行此處理程式:
+
+```javascript
+writer.onprogress = function() { /*commands*/ };
+```
+
+## 升級筆記
+
+在這個外掛程式 v1.0.0,`FileEntry` 和 `DirectoryEntry` 的結構已經改變,以更加一致的已發表說明書。
+
+以前 (pre-1.0.0) 版本的外掛程式中 `輸入` 物件的 `完整路徑` 屬性存放裝置固定檔案位置。這些路徑通常會看起來像
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+這些路徑還返回的 `Entry` 物件的 `toURL()` 方法。
+
+與 v1.0.0,`完整路徑` 屬性是到檔中,*相對於 HTML 檔案系統的根目錄* 的路徑。 因此,上述路徑會現在都由一個 `FileEntry` 物件的 `完整路徑`,
+
+ /path/to/file
+
+
+如果您的應用程式與設備-絕對路徑,並且您以前檢索到這些路徑通過 `條目` 物件的 `完整路徑` 屬性,然後您應該更新您的代碼以改用 `entry.toURL()`。
+
+為向後相容性,`resolveLocalFileSystemURL()` 方法將接受一個設備-絕對路徑,並將返回相應的 `條目` 物件,只要在 `臨時` 或 `永久性` 的檔案系統內的檔是否存在。
+
+這尤其是一直與檔案傳輸外掛程式,以前使用設備絕對路徑的問題 (和仍然可以接受他們)。 已更新它能夠正常運行與檔案系統的 Url,所以用 `entry.toURL()` 替換 `entry.fullPath` 應解決任何問題,得到該外掛程式來處理設備上的檔。
+
+在 v1.1.0 `toURL()` 的傳回值被更改 (見 [CB-6394] (HTTPs://issues.apache.org/jira/browse/CB-6394)) 為返回絕對 file:// URL。 只要有可能。 確保 'cdvfile:' — — 你現在可以用 `toInternalURL()` 的 URL。 現在,此方法將返回檔案系統表單的 Url
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+它可以用於唯一地標識該檔。
+
+## 錯誤代碼及其含義的清單中
+
+當拋出一個錯誤時,將使用以下代碼之一。
+
+| 代碼 | 恒 |
+| --:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## 配置外掛程式 (可選)
+
+可用的檔案系統的一整套可以配置每個平臺。IOS 和安卓系統認識到 在 `config.xml` 名稱要安裝的檔案系統中的標記。預設情況下,啟用所有檔案系統的根。
+
+
+
+
+
+### Android 系統
+
+ * `files`: 該應用程式的內部檔存儲目錄
+ * `files-external`: 應用程式的外部檔存儲目錄
+ * `sdcard`: 全球外部檔存儲目錄 (如果安裝了一個,這是 SD 卡的根目錄)。 你必須具有 `android.permission.WRITE_EXTERNAL_STORAGE` 許可權,用這個。
+ * `cache`: 應用程式的內部緩存目錄
+ * `cache-external`: 應用程式的外部快取記憶體目錄
+ * `root`: 整個設備的檔案系統
+
+安卓系統還支援特殊的檔命名為"檔",表示"/ 檔 /""檔"的檔案系統中的子目錄。
+
+### iOS
+
+ * `library`: 應用程式的庫目錄
+ * `documents`: 應用程式的檔目錄
+ * `cache`: 應用程式的緩存目錄
+ * `bundle`: 應用程式的包 ;應用程式本身 (唯讀) 的磁片上的位置
+ * `root`: 整個設備的檔案系統
+
+預設情況下,圖書館和檔目錄可以同步到 iCloud。 您也可以要求兩個額外的檔案系統、 `library-nosync` 和 `documents-nosync`,代表一個特殊的非同步目錄內 `/Library` 或 `/Documents` 的檔案系統。
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/doc/zh/index.md b/plugins/cordova-plugin-file/doc/zh/index.md
new file mode 100644
index 0000000..6eec44d
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/zh/index.md
@@ -0,0 +1,343 @@
+
+
+# cordova-plugin-file
+
+這個外掛程式實現檔 API 允許對檔駐留在該設備上的讀/寫訪問。
+
+這個外掛程式基於幾個規格,包括: HTML5 檔 API [HTTP://www.w3.org/TR/FileAPI/][1]
+
+ [1]: http://www.w3.org/TR/FileAPI/
+
+(現已解散) 目錄和系統擴展最新: [HTTP://www.w3.org/TR/2012/WD-file-system-api-20120417/][2]雖然大部分的外掛程式代碼寫時較早的規格是當前: [HTTP://www.w3.org/TR/2011/WD-file-system-api-20110419/][3]
+
+ [2]: http://www.w3.org/TR/2012/WD-file-system-api-20120417/
+ [3]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/
+
+它還實現 FileWriter 規格: [HTTP://dev.w3.org/2009/dap/file-system/file-writer.html][4]
+
+ [4]: http://dev.w3.org/2009/dap/file-system/file-writer.html
+
+用法,請參閱對 HTML5 的岩石優秀[檔案系統文章。][5]
+
+ [5]: http://www.html5rocks.com/en/tutorials/file/filesystem/
+
+其他存儲選項的概述,請參閱科爾多瓦的[存儲指南][6].
+
+ [6]: http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html
+
+這個外掛程式定義全球 `cordova.file` 物件。
+
+雖然在全球範圍內,它不可用直到 `deviceready` 事件之後。
+
+ document.addEventListener("deviceready", onDeviceReady, false);
+ function onDeviceReady() {
+ console.log(cordova.file);
+ }
+
+
+## 安裝
+
+ cordova plugin add cordova-plugin-file
+
+
+## 支援的平臺
+
+* 亞馬遜火 OS
+* Android 系統
+* 黑莓 10
+* 火狐瀏覽器的作業系統
+* iOS
+* Windows Phone 7 和 8 *
+* Windows 8 *
+* 瀏覽器
+
+* *這些平臺不支援 `FileReader.readAsArrayBuffer` 或 `FileWriter.write(blob)`.*
+
+## 存儲檔的位置
+
+截至 v1.2.0,提供重要的檔案系統目錄的 Url。 每個 URL 位於表單 *file:///path/to/spot/*,和可以轉換為使用 `window.resolveLocalFileSystemURL()` 的 `DirectoryEntry`.
+
+* `cordova.file.applicationDirectory`-唯讀目錄在哪裡安裝的應用程式。(*iOS*、*安卓*、*黑莓 10*)
+
+* `cordova.file.applicationStorageDirectory`-根目錄下的應用程式的沙箱 ;在 iOS 上此位置是唯讀 (但特定的子目錄 [像 `/Documents` ] 都是讀寫)。 中包含的所有資料都是私有的應用程式。 ( *iOS*、*安卓*、*黑莓 10*)
+
+* `cordova.file.dataDirectory`資料持久性和私有資料存儲在內部記憶體使用的應用程式的沙箱內 (在安卓系統,如果你需要使用外部儲存體,使用 `.externalDataDirectory` )。 在 iOS,此目錄不與 iCloud 同步 (使用 `.syncedDataDirectory` )。 (*iOS*、*安卓*、*黑莓 10*)
+
+* `cordova.file.cacheDirectory`-緩存的資料檔案或您的應用程式重新可以輕鬆地創建的任何檔的目錄。 作業系統可能會刪除這些檔,該設備在存儲上運行低時,然而,應用程式不應依賴的作業系統,請刪除檔在這裡。 (*iOS*、*安卓*、*黑莓 10*)
+
+* `cordova.file.externalApplicationStorageDirectory`-應用程式外部存儲上的空間。(*安卓*)
+
+* `cordova.file.externalDataDirectory`-放在外部存儲特定于應用程式的資料檔案的位置。(*安卓*)
+
+* `cordova.file.externalCacheDirectory`-在外部存儲應用程式緩存。(*安卓*)
+
+* `cordova.file.externalRootDirectory`-外部存儲 (SD 卡) 的根。(*安卓*、*黑莓 10*)
+
+* `cordova.file.tempDirectory`-OS 可以清除時的空目錄會。 不依賴于 OS,以清除此目錄 ;您的應用程式,應總是移除作為適用的檔。 (*iOS*)
+
+* `cordova.file.syncedDataDirectory`-保存應同步 (例如到 iCloud) 的特定于應用程式的檔。(*iOS*)
+
+* `cordova.file.documentsDirectory`-檔私有的應用程式,但這是對其他應用程式 (例如 Office 檔) 有意義。(*iOS*)
+
+* `cordova.file.sharedDirectory`-對所有應用程式 (*黑莓 10*全域可用的檔)
+
+## 檔案系統佈局
+
+雖然技術上實現的細節,它可以是很有必要瞭解如何 `cordova.file.*` 屬性對應到實體路徑在實際設備上。
+
+### iOS 檔案系統佈局
+
+| 設備路徑 | `cordova.file.*` | `iosExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 同步 | 私人 |
+|:------------------------------- |:--------------------------- |:--------------------- |:------:|:------:|:----------:|:---:|:--:|
+| `/ 無功/移動/應用程式/< UUID > /` | applicationStorageDirectory | - | r | 不適用 | 不適用 | 不適用 | 是啊 |
+| `appname.app/` | applicationDirectory | 束 | r | 不適用 | 不適用 | 不適用 | 是啊 |
+| `www/` | - | - | r | 不適用 | 不適用 | 不適用 | 是啊 |
+| `Documents/` | documentsDirectory | 檔 | r/w | 是啊 | 無 | 是啊 | 是啊 |
+| `NoCloud/` | - | 檔 nosync | r/w | 是啊 | 無 | 無 | 是啊 |
+| `Library` | - | 圖書館 | r/w | 是啊 | 無 | 是嗎? | 是啊 |
+| `NoCloud/` | dataDirectory | 圖書館 nosync | r/w | 是啊 | 無 | 無 | 是啊 |
+| `Cloud/` | syncedDataDirectory | - | r/w | 是啊 | 無 | 是啊 | 是啊 |
+| `Caches/` | cacheDirectory | 快取記憶體 | r/w | 是啊 * | 是的 * * *| | 無 | 是啊 |
+| `tmp/` | tempDirectory | - | r/w | 沒有 * * | 是的 * * *| | 無 | 是啊 |
+
+* 檔堅持跨應用程式重新開機和升級,但是每當作業系統的欲望,可以清除此目錄。您的應用程式應該能夠重新創建任何內容可能會被刪除。
+
+* * 檔可能會持續整個應用程式重新開機,但不要依賴此行為。 不保證檔在更新之間持續存在。 您的應用程式時適用,是應該刪除此目錄的檔,因為作業系統並不能保證何時 (或即使) 中刪除這些檔。
+
+* * *| 作業系統可能會清除此目錄的內容,每當它感覺它是必要的但不要依賴于此。 你應該清除此目錄為適合您的應用程式。
+
+### Android 的檔案系統佈局
+
+| 設備路徑 | `cordova.file.*` | `AndroidExtraFileSystems` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 |
+|:--------------------------------- |:----------------------------------- |:------------------------- |:------:|:-----:|:------:|:--:|
+| `file:///android_asset/` | applicationDirectory | | r | 不適用 | 不適用 | 是啊 |
+| `/ 資料資料/< 應用程式 id > /` | applicationStorageDirectory | - | r/w | 不適用 | 不適用 | 是啊 |
+| `cache` | cacheDirectory | 快取記憶體 | r/w | 是啊 | 是啊 * | 是啊 |
+| `files` | dataDirectory | 檔 | r/w | 是啊 | 無 | 是啊 |
+| `Documents` | | 檔 | r/w | 是啊 | 無 | 是啊 |
+| `< sd 卡 > /` | externalRootDirectory | sd 卡 | r/w | 是啊 | 無 | 無 |
+| `Android/data//` | externalApplicationStorageDirectory | - | r/w | 是啊 | 無 | 無 |
+| `cache` | externalCacheDirectry | 外部快取記憶體 | r/w | 是啊 | 沒有 * * | 無 |
+| `files` | externalDataDirectory | 外部檔 | r/w | 是啊 | 無 | 無 |
+
+* 的作業系統可能會定期清除此目錄中,但不是依賴于這種行為。 清除此為適合您的應用程式的目錄的內容。 使用者應手動清除緩存,將刪除此目錄的內容。
+
+* * 作業系統不會自動清除此目錄你是負責管理自己的內容。 使用者應手動清除緩存,目錄中的內容將被刪除。
+
+**注**: 如果外部存儲無法裝入,`cordova.file.external*` 屬性為 `空`.
+
+### 黑莓 10 檔案系統佈局
+
+| 設備路徑 | `cordova.file.*` | r/w 嗎? | 持續性嗎? | OS 清除 | 私人 |
+|:---------------------------------------------------- |:--------------------------- |:------:|:-----:|:-----:|:--:|
+| `file:///accounts/1000/appdata/ < 應用程式 id > /` | applicationStorageDirectory | r | 不適用 | 不適用 | 是啊 |
+| `app/native` | applicationDirectory | r | 不適用 | 不適用 | 是啊 |
+| `data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | 無 | 是啊 | 是啊 |
+| `data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | 是啊 | 無 | 是啊 |
+| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | 是啊 | 無 | 無 |
+| `file:///accounts/1000/shared` | sharedDirectory | r/w | 是啊 | 無 | 無 |
+
+*注意*: 當應用程式部署工作週邊時,所有路徑都是相對於 /accounts/1000-enterprise。
+
+## Android 的怪癖
+
+### Android 的持久性存儲位置
+
+有很多有效的位置來存儲持久性檔在 Android 設備上。 請參閱 [此頁面][7] 的各種可能性進行廣泛討論。
+
+ [7]: http://developer.android.com/guide/topics/data/data-storage.html
+
+以前版本的外掛程式會選擇在啟動時,基於該設備是否聲稱 SD 卡 (或等效存儲分區) 展開,臨時和永久檔的位置。 如果被掛載 SD 卡,或一個大的內部存儲分區可用 (如 nexus 系列設備上) 然後持久性檔將存儲在該空間的根目錄中。 這意味著所有的科爾多瓦應用程式可以看到所有可用的檔在卡片上。
+
+如果 SD 卡不是可用的那麼以前的版本中將存儲資料下的 `/data/data/`,其中隔離應用程式從彼此,但仍可能導致使用者之間共用的資料。
+
+現在可以選擇是否將檔存儲在內部檔的存儲位置,或使用以前的邏輯,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`:
+
+
+
+
+
+
+如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。
+
+如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到"Internal"的位置,將意味著現有使用者升級他們的應用程式可能無法訪問他們以前存儲的檔,具體取決於他們的設備。
+
+如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。
+
+## iOS 的怪癖
+
+* `cordova.file.applicationStorageDirectory`是唯讀的 ;試圖存儲內的根目錄中的檔將會失敗。 使用的另一個 `cordova.file.*` 為 iOS 定義的屬性 (只有 `applicationDirectory` 和 `applicationStorageDirectory` 都是唯讀)。
+* `FileReader.readAsText(blob, encoding)`
+ * `encoding`參數不受支援,而 utf-8 編碼總是效果。
+
+### iOS 的持久性存儲位置
+
+有兩個有效的位置來存儲持久性在 iOS 設備上的檔: 檔目錄和圖書館目錄。 以前版本的外掛程式永遠只能將持久性檔存儲在文檔目錄中。 這已經使所有應用程式檔可見在 iTunes,往往是無意為之,尤其是對於處理大量小檔的應用程式中,而不是生產供出口,該目錄的既定的目標是證件齊全的副作用。
+
+現在可以選擇是否將檔存儲在檔或庫目錄,與您的應用程式的 `config.xml` 檔中的偏好。 要執行此操作,請將以下兩行之一添加到 `config.xml`:
+
+
+
+
+
+
+如果這條線,沒有檔外掛程式將使用 `Compatibility` 作為預設值。如果首選項標記存在,並不是這些值之一,應用程式將無法啟動。
+
+如果您的應用程式以前已被運到使用者,使用較舊的 (預 1.0) 版本的這個外掛程式,並具有持久性的檔,系統中存儲的檔,然後您應該設置 `Compatibility` 偏好。 切換到 `Library` 的位置,將意味著現有使用者升級他們的應用程式將無法訪問他們以前存儲的檔。
+
+如果您的應用程式是新的或以前從未有持久性的檔案系統中存儲檔,那麼通常建議使用 `Internal` 設置。
+
+## 火狐瀏覽器作業系統的怪癖
+
+檔案系統 API 本身不支援火狐瀏覽器的作業系統,作為墊片在 indexedDB 上實現的。
+
+* 不會失敗時刪除非空的目錄
+* 不支援中繼資料的目錄
+* 方法 `copyTo` 和 `moveTo` 不支援目錄
+
+支援以下資料路徑: * `applicationDirectory`-使用 `xhr` 獲取與應用程式打包的本地檔。 `dataDirectory`-用於持久性的特定于應用程式的資料檔案。 `cacheDirectory`-生存應重新開機應用程式的快取檔案 (應用程式不應依賴作業系統來刪除檔在這裡)。
+
+## 瀏覽器的怪癖
+
+### 常見的怪癖和備註
+
+* 每個瀏覽器使用其自己的沙箱檔案系統。IE 和火狐瀏覽器使用 IndexedDB 作為一個基地。所有瀏覽器都使用正斜杠作為路徑中的目錄分隔符號。
+* 目錄條目不得不先後創建。 例如,調用 `fs.root.getDirectory (' dir1/dir2 ',{create:true},successCallback,errorCallback)`,如果不存在 dir1 將失敗。
+* 外掛程式將請求使用者許可權,以便在應用程式初次開機使用持久性存儲。
+* 外掛程式支援 `cdvfile://localhost` (本地資源) 只。通過 `cdvfile` 不支援外部資源即.
+* 該外掛程式不遵循 ["檔案系統 API 8.3 命名限制"][8].
+* Blob 和檔 ' `close` 功能不受支援。
+* `FileSaver` 和 `BlobBuilder` 不支援這個外掛程式,沒有存根 (stub)。
+* 該外掛程式不支援 `requestAllFileSystems`。這個功能也是缺少規範中。
+* 在目錄中的條目將不會被刪除,如果您使用 `create: true` 標誌為現有目錄。
+* 不支援通過建構函式創建的檔。你應該使用 entry.file 方法。
+* 每個瀏覽器使用它自己的形式為 blob 的 URL 引用。
+* 支援 `readAsDataURL` 功能,但在 Chrome 中的媒體類型取決於輸入副檔名,在 IE 中的媒體類型都始終空著 (這是 `純文字` 按照說明書一樣),在 Firefox 中的媒體類型始終是 `應用程式/八位位元組流`。 例如,如果內容是 `abcdefg` 然後火狐瀏覽器返回 `資料: 應用程式 / 八位位元組流 ; base64,YWJjZGVmZw = =`,即返回 `資料: ; base64,YWJjZGVmZw = =`,鉻返回 `資料: < 媒體類型根據擴展條目名稱 > ; base64,YWJjZGVmZw = =`.
+* 在表單 `file:///persistent/path/to/entry` 火狐瀏覽器 IE),`toInternalURL` 返回的路徑。 鉻在表單 `cdvfile://localhost/persistent/file` 返回的路徑.
+
+ [8]: http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions
+
+### 鉻的怪癖
+
+* 設備準備好事件之後,chrome 檔案系統並不能立即準備。作為一種變通方法,您可以訂閱到 `filePluginIsReady` 事件。示例:
+
+ javascript
+ window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
+
+
+你可以使用 `window.isFilePluginReadyRaised` 函數來檢查是否已經引發了事件。 -window.requestFileSystem 臨時和永久性檔案系統配額並不局限于鉻。 為增加中鉻的持久性存儲,您需要調用 `window.initPersistentFileSystem` 方法。 預設情況下,持久性存儲配額為 5 MB。 鉻需要 `— — 允許--訪問-從-檔` 通過 `file:///` 協定運行參數對 API 的支援。 -如果您使用標誌,將不更改 `檔` 物件 `{create:true}` 現有 `條目` 的時候。 -事件 `可取消` 屬性設置為 true 在 Chrome 中。 這是違反了 [規範][4]。 -中鉻的 `toURL` 函數返回 `檔案系統:`-首碼路徑具體取決於應用程式主機。 例如,`filesystem:file:///persistent/somefile.txt`,`filesystem:HTTP://localhost:8080/persistent/somefile.txt`。 -`toURL` 函數結果不包含尾部反斜線在目錄條目的情況下。 鉻雖然正確解析目錄帶斜杠落後的 url。 -`resolveLocalFileSystemURL` 方法需要入站的 `url` 必須具有 `檔案系統` 首碼。 例如,`resolveLocalFileSystemURL` 的 `url` 參數應在表單 `filesystem:file:///persistent/somefile.txt` 而不是表單 `file:///persistent/somefile.txt` 在安卓系統。 -不推薦使用 `toNativeURL` 函數不受支援,並且沒有存根 (stub)。 -`setMetadata` 功能是沒有說出的規格,並且不支援。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 SYNTAX_ERR(code: 8) 上請求一個不存在的檔案系統。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 PATH_EXISTS_ERR(code: 12) 上嘗試專門創建一個檔或目錄,它已經存在。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NO_MODIFICATION_ALLOWED_ERR(code: 6) 在試圖調用 removeRecursively 的根檔案系統上。 -INVALID_MODIFICATION_ERR (代碼: 9) 而不是引發 NOT_FOUND_ERR(code: 1) 試到 moveTo 目錄不存在。
+
+### 基於 IndexedDB 的 impl 怪癖 (Firefox 和 IE)
+
+* `.` 和 `.` 不受支援。
+* IE 不支援 `file:///`-模式 ;只有託管的模式是支援 (HTTP://localhost:xxxx)。
+* 火狐瀏覽器的檔案系統大小不是有限,但每個 50 MB 擴展會要求使用者的許可權。 IE10 允許達 10 mb 的 AppCache 和 IndexedDB 檔案系統的實現中使用而不會提示,一旦你達到這一水準你會詢問您是否允許它增加到每個網站的 250 mb 的最大合併。 所以 `requestFileSystem` 函數的 `大小` 參數並不影響檔案系統相容 Firefox 和 IE。
+* `readAsBinaryString` 函數在規範中沒有注明不支援在 IE 中和沒有存根 (stub)。
+* `file.type` 始終為 null。
+* 您不應創建條目使用已刪除的目錄實例回檔結果。否則,你會得到一個 '掛條目'。
+* 您可以讀取一個檔,其中只是寫之前你需要獲得的此檔的新實例。
+* `setMetadata` 函數,在規範中沒有注明支援 `modificationTime` 欄位的更改。
+* `copyTo` 和 `moveTo` 函數不支援目錄。
+* 不支援目錄的中繼資料。
+* 兩個 Entry.remove 和 directoryEntry.removeRecursively 不失敗時刪除非空的目錄-相反與內容一起清理目錄被刪除。
+* 不支援 `abort` 和 `truncate` 函數。
+* 進度事件不會觸發。例如,將不執行此處理程式:
+
+ javascript
+ writer.onprogress = function() { /*commands*/ };
+
+
+## 升級筆記
+
+在這個外掛程式 v1.0.0,`FileEntry` 和 `DirectoryEntry` 的結構已經改變,以更加一致的已發表說明書。
+
+以前 (pre-1.0.0) 版本的外掛程式中 `輸入` 物件的 `完整路徑` 屬性存放裝置固定檔案位置。這些路徑通常會看起來像
+
+ /var/mobile/Applications//Documents/path/to/file (iOS)
+ /storage/emulated/0/path/to/file (Android)
+
+
+這些路徑還返回的 `Entry` 物件的 `toURL()` 方法。
+
+與 v1.0.0,`完整路徑` 屬性是到檔中,*相對於 HTML 檔案系統的根目錄* 的路徑。 因此,上述路徑會現在都由一個 `FileEntry` 物件的 `完整路徑`,
+
+ /path/to/file
+
+
+如果您的應用程式與設備-絕對路徑,並且您以前檢索到這些路徑通過 `條目` 物件的 `完整路徑` 屬性,然後您應該更新您的代碼以改用 `entry.toURL()`。
+
+為向後相容性,`resolveLocalFileSystemURL()` 方法將接受一個設備-絕對路徑,並將返回相應的 `條目` 物件,只要在 `臨時` 或 `永久性` 的檔案系統內的檔是否存在。
+
+這尤其是一直與檔案傳輸外掛程式,以前使用設備絕對路徑的問題 (和仍然可以接受他們)。 已更新它能夠正常運行與檔案系統的 Url,所以用 `entry.toURL()` 替換 `entry.fullPath` 應解決任何問題,得到該外掛程式來處理設備上的檔。
+
+在 v1.1.0 `toURL()` 的傳回值被更改 (見 [CB-6394] (HTTPs://issues.apache.org/jira/browse/CB-6394)) 為返回絕對 file:// URL。 只要有可能。 確保 'cdvfile:' — — 你現在可以用 `toInternalURL()` 的 URL。 現在,此方法將返回檔案系統表單的 Url
+
+ cdvfile://localhost/persistent/path/to/file
+
+
+它可以用於唯一地標識該檔。
+
+## 錯誤代碼及其含義的清單中
+
+當拋出一個錯誤時,將使用以下代碼之一。
+
+| 代碼 | 恒 |
+| --:|:----------------------------- |
+| 1 | `NOT_FOUND_ERR` |
+| 2 | `SECURITY_ERR` |
+| 3 | `ABORT_ERR` |
+| 4 | `NOT_READABLE_ERR` |
+| 5 | `ENCODING_ERR` |
+| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
+| 7 | `INVALID_STATE_ERR` |
+| 8 | `SYNTAX_ERR` |
+| 9 | `INVALID_MODIFICATION_ERR` |
+| 10 | `QUOTA_EXCEEDED_ERR` |
+| 11 | `TYPE_MISMATCH_ERR` |
+| 12 | `PATH_EXISTS_ERR` |
+
+## 配置外掛程式 (可選)
+
+可用的檔案系統的一整套可以配置每個平臺。IOS 和安卓系統認識到 在 `config.xml` 名稱要安裝的檔案系統中的標記。預設情況下,啟用所有檔案系統的根。
+
+
+
+
+
+### Android 系統
+
+* `files`: 該應用程式的內部檔存儲目錄
+* `files-external`: 應用程式的外部檔存儲目錄
+* `sdcard`: 全球外部檔存儲目錄 (如果安裝了一個,這是 SD 卡的根目錄)。 你必須具有 `android.permission.WRITE_EXTERNAL_STORAGE` 許可權,用這個。
+* `cache`: 應用程式的內部緩存目錄
+* `cache-external`: 應用程式的外部快取記憶體目錄
+* `root`: 整個設備的檔案系統
+
+安卓系統還支援特殊的檔命名為"檔",表示"/ 檔 /""檔"的檔案系統中的子目錄。
+
+### iOS
+
+* `library`: 應用程式的庫目錄
+* `documents`: 應用程式的檔目錄
+* `cache`: 應用程式的緩存目錄
+* `bundle`: 應用程式的包 ;應用程式本身 (唯讀) 的磁片上的位置
+* `root`: 整個設備的檔案系統
+
+預設情況下,圖書館和檔目錄可以同步到 iCloud。 您也可以要求兩個額外的檔案系統、 `library-nosync` 和 `documents-nosync`,代表一個特殊的非同步目錄內 `/Library` 或 `/Documents` 的檔案系統。
diff --git a/plugins/cordova-plugin-file/doc/zh/plugins.md b/plugins/cordova-plugin-file/doc/zh/plugins.md
new file mode 100644
index 0000000..c9a2d61
--- /dev/null
+++ b/plugins/cordova-plugin-file/doc/zh/plugins.md
@@ -0,0 +1,101 @@
+
+
+# 外掛程式開發人員注意事項
+
+這些筆記主要用於 Android 和 iOS 開發者想要編寫外掛程式的介面與使用檔外掛程式的檔案系統。
+
+## 工作與科爾多瓦檔案系統 Url
+
+自從版本 1.0.0,這個外掛程式一直使用 Url 與 `cdvfile` 大橋,計畫為所有通信,而不是揭露 JavaScript 的原始設備檔案系統路徑。
+
+在 JavaScript 方面,這意味著 FileEntry 和 DirectoryEntry 的物件有一個完整路徑屬性是相對於 HTML 檔案系統的根目錄。 如果你的外掛程式的 JavaScript API 接受一個 FileEntry 或 DirectoryEntry 的物件,你應該打電話給 `.toURL()` 對該物件之前將它從橋上傳遞給本機代碼。
+
+### 轉換 cdvfile: / / fileystem 路徑的 Url
+
+需要寫入到檔案系統的外掛程式可能想要將接收的檔案系統 URL 轉換為實際的檔案系統位置。有做這,根據本機平臺的多種方式。
+
+很重要的是要記住,並不是所有 `cdvfile://` Url 是可映射到設備上的實際檔。 某些 Url 可以指在設備上沒有代表的檔,或甚至可以引用遠端資源的資產。 由於這些可能性,外掛程式應始終測試是否回來時試圖將 Url 轉換成路徑得到有意義的結果。
+
+#### 安卓系統
+
+在 android 系統,最簡單的方法來轉換 `cdvfile://` 檔案系統路徑的 URL 是使用 `org.apache.cordova.CordovaResourceApi` 。 `CordovaResourceApi`有幾種方法,可處理 `cdvfile://` 網址:
+
+ web 視圖是成員的外掛程式類 CordovaResourceApi resourceApi = webView.getResourceApi();
+
+ 獲取表示此檔在設備上,file:/// URL / / 或 URL 相同變的如果它不能映射到檔 Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
+
+
+它也是可以直接使用檔外掛程式:
+
+ 導入 org.apache.cordova.file.FileUtils;
+ 導入 org.apache.cordova.file.FileSystem;
+ 導入 java.net.MalformedURLException;
+
+ 得到檔外掛程式外掛程式管理器從 FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
+
+ 給定 URL,得到的路徑,因為它嘗試 {字串路徑 = filePlugin.filesystemPathForURL(cdvfileURL);} 趕上 (MalformedURLException e) {/ / 檔案系統 url 不承認}
+
+
+要轉換到的路徑從 `cdvfile://` URL:
+
+ 導入 org.apache.cordova.file.LocalFilesystemURL;
+
+ 獲取設備的路徑,一個 LocalFilesystemURL 物件 / / 或如果它不能表示為 cdvfile 的 URL,則為 null。
+ LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
+ 得到的字串表示形式的 URL 物件字串 cdvfileURL = url.toString();
+
+
+如果你的外掛程式創建一個檔,並且您想要為它返回一個 FileEntry 物件,使用該檔的外掛程式:
+
+ 返回一個 JSON 結構適合於回到 JavaScript,/ / 或如果此檔不是可表示為 cdvfile 的 URL,則為 null。
+ JSONObject 條目 = filePlugin.getEntryForFile(file);
+
+
+#### iOS
+
+科爾多瓦在 iOS 上的不使用相同 `CordovaResourceApi` 作為 android 系統的概念。在 iOS,應使用檔外掛程式 Url 和檔案系統路徑之間進行轉換。
+
+ 獲取一個物件,CDVFilesystem URL 從 url 字串 CDVFilesystemURL * = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
+ 獲取路徑 URL 物件,或為零,如果它不能映射到檔 NSString * 路徑 = [filePlugin filesystemPathForURL:url];
+
+
+ CDVFilesystem URL 物件獲取設備的路徑,或 / / 為零,如果它不能表示為 cdvfile 的 URL。
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ 得到的字串表示形式的 URL 物件 NSString * cdvfileURL = [url absoluteString];
+
+
+如果你的外掛程式創建一個檔,並且您想要為它返回一個 FileEntry 物件,使用該檔的外掛程式:
+
+ CDVFilesystem URL 物件獲取設備的路徑,或 / / 為零,如果它不能表示為 cdvfile 的 URL。
+ CDVFilesystemURL * url = [filePlugin fileSystemURLforLocalPath:path];
+ 得到一個結構來返回進入 JavaScript NSDictionary * = [filePlugin makeEntryForLocalURL:url]
+
+
+#### JavaScript
+
+在 JavaScript 中,得到 `cdvfile://` URL 從 FileEntry 或 DirectoryEntry 的物件,只需調用 `.toURL()` 對它:
+
+ var cdvfileURL = entry.toURL();
+
+
+在外掛程式回應處理常式,將從返回的 FileEntry 結構轉換為實際的條目物件,處理常式代碼應該導入檔外掛程式和創建新的物件:
+
+ 創建適當的條目物件 var 條目;
+ 如果 (entryStruct.isDirectory) {條目 = 新目錄 (entryStruct.name,entryStruct.fullPath,新 FileSystem(entryStruct.filesystemName));} 其他 {條目 = 新的 FileEntry (entryStruct.name,entryStruct.fullPath,新 FileSystem(entryStruct.filesystemName));}
\ No newline at end of file
diff --git a/plugins/cordova-plugin-file/package.json b/plugins/cordova-plugin-file/package.json
new file mode 100644
index 0000000..3fc292a
--- /dev/null
+++ b/plugins/cordova-plugin-file/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "cordova-plugin-file",
+ "version": "3.0.0",
+ "description": "Cordova File Plugin",
+ "cordova": {
+ "id": "cordova-plugin-file",
+ "platforms": [
+ "android",
+ "amazon-fireos",
+ "ubuntu",
+ "ios",
+ "wp7",
+ "wp8",
+ "blackberry10",
+ "windows8",
+ "windows",
+ "firefoxos"
+ ]
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/apache/cordova-plugin-file"
+ },
+ "keywords": [
+ "cordova",
+ "file",
+ "ecosystem:cordova",
+ "cordova-android",
+ "cordova-amazon-fireos",
+ "cordova-ubuntu",
+ "cordova-ios",
+ "cordova-wp7",
+ "cordova-wp8",
+ "cordova-blackberry10",
+ "cordova-windows8",
+ "cordova-windows",
+ "cordova-firefoxos"
+ ],
+ "author": "Apache Software Foundation",
+ "license": "Apache 2.0"
+}
diff --git a/plugins/cordova-plugin-file/plugin.xml b/plugins/cordova-plugin-file/plugin.xml
new file mode 100644
index 0000000..7296f95
--- /dev/null
+++ b/plugins/cordova-plugin-file/plugin.xml
@@ -0,0 +1,385 @@
+
+
+
+
+ File
+ Cordova File Plugin
+ Apache 2.0
+ cordova,file
+ https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
+ https://issues.apache.org/jira/browse/CB/component/12320651
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+The Android Persistent storage location now defaults to "Internal". Please check this plugins README to see if you application needs any changes in its config.xml.
+
+If this is a new application no changes are required.
+
+If this is an update to an existing application that did not specify an "AndroidPersistentFileLocation" you may need to add:
+
+ "<preference name="AndroidPersistentFileLocation" value="Compatibility" />"
+
+to config.xml in order for the application to find previously stored files.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugins/cordova-plugin-file/src/android/AssetFilesystem.java b/plugins/cordova-plugin-file/src/android/AssetFilesystem.java
new file mode 100644
index 0000000..f501b27
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/AssetFilesystem.java
@@ -0,0 +1,283 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.content.res.AssetManager;
+import android.net.Uri;
+import android.util.Log;
+
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+public class AssetFilesystem extends Filesystem {
+
+ private final AssetManager assetManager;
+
+ // A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne.
+ // See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow
+ private static Object listCacheLock = new Object();
+ private static boolean listCacheFromFile;
+ private static Map listCache;
+ private static Map lengthCache;
+
+ private void lazyInitCaches() {
+ synchronized (listCacheLock) {
+ if (listCache == null) {
+ ObjectInputStream ois = null;
+ try {
+ ois = new ObjectInputStream(assetManager.open("cdvasset.manifest"));
+ listCache = (Map) ois.readObject();
+ lengthCache = (Map) ois.readObject();
+ listCacheFromFile = true;
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ // Asset manifest won't exist if the gradle hook isn't set up correctly.
+ } finally {
+ if (ois != null) {
+ try {
+ ois.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ if (listCache == null) {
+ Log.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow.");
+ listCache = new HashMap();
+ }
+ }
+ }
+ }
+
+ private String[] listAssets(String assetPath) throws IOException {
+ if (assetPath.startsWith("/")) {
+ assetPath = assetPath.substring(1);
+ }
+ lazyInitCaches();
+ String[] ret = listCache.get(assetPath);
+ if (ret == null) {
+ if (listCacheFromFile) {
+ ret = new String[0];
+ } else {
+ ret = assetManager.list(assetPath);
+ listCache.put(assetPath, ret);
+ }
+ }
+ return ret;
+ }
+
+ private long getAssetSize(String assetPath) throws FileNotFoundException {
+ if (assetPath.startsWith("/")) {
+ assetPath = assetPath.substring(1);
+ }
+ lazyInitCaches();
+ if (lengthCache != null) {
+ Long ret = lengthCache.get(assetPath);
+ if (ret == null) {
+ throw new FileNotFoundException("Asset not found: " + assetPath);
+ }
+ return ret;
+ }
+ CordovaResourceApi.OpenForReadResult offr = null;
+ try {
+ offr = resourceApi.openForRead(nativeUriForFullPath(assetPath));
+ long length = offr.length;
+ if (length < 0) {
+ // available() doesn't always yield the file size, but for assets it does.
+ length = offr.inputStream.available();
+ }
+ return length;
+ } catch (IOException e) {
+ throw new FileNotFoundException("File not found: " + assetPath);
+ } finally {
+ if (offr != null) {
+ try {
+ offr.inputStream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+
+ public AssetFilesystem(AssetManager assetManager, CordovaResourceApi resourceApi) {
+ super(Uri.parse("file:///android_asset/"), "assets", resourceApi);
+ this.assetManager = assetManager;
+ }
+
+ @Override
+ public Uri toNativeUri(LocalFilesystemURL inputURL) {
+ return nativeUriForFullPath(inputURL.path);
+ }
+
+ @Override
+ public LocalFilesystemURL toLocalUri(Uri inputURL) {
+ if (!"file".equals(inputURL.getScheme())) {
+ return null;
+ }
+ File f = new File(inputURL.getPath());
+ // Removes and duplicate /s (e.g. file:///a//b/c)
+ Uri resolvedUri = Uri.fromFile(f);
+ String rootUriNoTrailingSlash = rootUri.getEncodedPath();
+ rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
+ if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
+ return null;
+ }
+ String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
+ // Strip leading slash
+ if (!subPath.isEmpty()) {
+ subPath = subPath.substring(1);
+ }
+ Uri.Builder b = new Uri.Builder()
+ .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
+ .authority("localhost")
+ .path(name);
+ if (!subPath.isEmpty()) {
+ b.appendEncodedPath(subPath);
+ }
+ if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
+ // Add trailing / for directories.
+ b.appendEncodedPath("");
+ }
+ return LocalFilesystemURL.parse(b.build());
+ }
+
+ private boolean isDirectory(String assetPath) {
+ try {
+ return listAssets(assetPath).length != 0;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ String pathNoSlashes = inputURL.path.substring(1);
+ if (pathNoSlashes.endsWith("/")) {
+ pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
+ }
+
+ String[] files;
+ try {
+ files = listAssets(pathNoSlashes);
+ } catch (IOException e) {
+ throw new FileNotFoundException();
+ }
+
+ LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
+ for (int i = 0; i < files.length; ++i) {
+ entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
+ }
+ return entries;
+ }
+
+ @Override
+ public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
+ String path, JSONObject options, boolean directory)
+ throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ if (options != null && options.optBoolean("create")) {
+ throw new UnsupportedOperationException("Assets are read-only");
+ }
+
+ // Check whether the supplied path is absolute or relative
+ if (directory && !path.endsWith("/")) {
+ path += "/";
+ }
+
+ LocalFilesystemURL requestedURL;
+ if (path.startsWith("/")) {
+ requestedURL = localUrlforFullPath(normalizePath(path));
+ } else {
+ requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
+ }
+
+ // Throws a FileNotFoundException if it doesn't exist.
+ getFileMetadataForLocalURL(requestedURL);
+
+ boolean isDir = isDirectory(requestedURL.path);
+ if (directory && !isDir) {
+ throw new TypeMismatchException("path doesn't exist or is file");
+ } else if (!directory && isDir) {
+ throw new TypeMismatchException("path doesn't exist or is directory");
+ }
+
+ // Return the directory
+ return makeEntryForURL(requestedURL);
+ }
+
+ @Override
+ public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ JSONObject metadata = new JSONObject();
+ long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path);
+ try {
+ metadata.put("size", size);
+ metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL)));
+ metadata.put("name", new File(inputURL.path).getName());
+ metadata.put("fullPath", inputURL.path);
+ metadata.put("lastModifiedDate", 0);
+ } catch (JSONException e) {
+ return null;
+ }
+ return metadata;
+ }
+
+ @Override
+ public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
+ return false;
+ }
+
+ @Override
+ long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+ @Override
+ long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+ @Override
+ String filesystemPathForURL(LocalFilesystemURL url) {
+ return null;
+ }
+
+ @Override
+ LocalFilesystemURL URLforFilesystemPath(String path) {
+ return null;
+ }
+
+ @Override
+ boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+ @Override
+ boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Assets are read-only");
+ }
+
+}
diff --git a/plugins/cordova-plugin-file/src/android/ContentFilesystem.java b/plugins/cordova-plugin-file/src/android/ContentFilesystem.java
new file mode 100644
index 0000000..eab0b03
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/ContentFilesystem.java
@@ -0,0 +1,215 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.MediaStore;
+import android.provider.OpenableColumns;
+
+public class ContentFilesystem extends Filesystem {
+
+ private final Context context;
+
+ public ContentFilesystem(Context context, CordovaResourceApi resourceApi) {
+ super(Uri.parse("content://"), "content", resourceApi);
+ this.context = context;
+ }
+
+ @Override
+ public Uri toNativeUri(LocalFilesystemURL inputURL) {
+ String authorityAndPath = inputURL.uri.getEncodedPath().substring(this.name.length() + 2);
+ if (authorityAndPath.length() < 2) {
+ return null;
+ }
+ String ret = "content://" + authorityAndPath;
+ String query = inputURL.uri.getEncodedQuery();
+ if (query != null) {
+ ret += '?' + query;
+ }
+ String frag = inputURL.uri.getEncodedFragment();
+ if (frag != null) {
+ ret += '#' + frag;
+ }
+ return Uri.parse(ret);
+ }
+
+ @Override
+ public LocalFilesystemURL toLocalUri(Uri inputURL) {
+ if (!"content".equals(inputURL.getScheme())) {
+ return null;
+ }
+ String subPath = inputURL.getEncodedPath();
+ if (subPath.length() > 0) {
+ subPath = subPath.substring(1);
+ }
+ Uri.Builder b = new Uri.Builder()
+ .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
+ .authority("localhost")
+ .path(name)
+ .appendPath(inputURL.getAuthority());
+ if (subPath.length() > 0) {
+ b.appendEncodedPath(subPath);
+ }
+ Uri localUri = b.encodedQuery(inputURL.getEncodedQuery())
+ .encodedFragment(inputURL.getEncodedFragment())
+ .build();
+ return LocalFilesystemURL.parse(localUri);
+ }
+
+ @Override
+ public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
+ String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
+ throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead.");
+ }
+
+ @Override
+ public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL)
+ throws NoModificationAllowedException {
+ Uri contentUri = toNativeUri(inputURL);
+ try {
+ context.getContentResolver().delete(contentUri, null, null);
+ } catch (UnsupportedOperationException t) {
+ // Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
+ // The ContentResolver applies only when the file was registered in the
+ // first case, which is generally only the case with images.
+ throw new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL)
+ throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Cannot remove content url");
+ }
+
+ @Override
+ public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead.");
+ }
+
+ @Override
+ public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ long size = -1;
+ long lastModified = 0;
+ Uri nativeUri = toNativeUri(inputURL);
+ String mimeType = resourceApi.getMimeType(nativeUri);
+ Cursor cursor = openCursorForURL(nativeUri);
+ try {
+ if (cursor != null && cursor.moveToFirst()) {
+ size = resourceSizeForCursor(cursor);
+ lastModified = lastModifiedDateForCursor(cursor);
+ } else {
+ // Some content providers don't support cursors at all!
+ CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri);
+ size = offr.length;
+ }
+ } catch (IOException e) {
+ throw new FileNotFoundException();
+ } finally {
+ if (cursor != null)
+ cursor.close();
+ }
+
+ JSONObject metadata = new JSONObject();
+ try {
+ metadata.put("size", size);
+ metadata.put("type", mimeType);
+ metadata.put("name", name);
+ metadata.put("fullPath", inputURL.path);
+ metadata.put("lastModifiedDate", lastModified);
+ } catch (JSONException e) {
+ return null;
+ }
+ return metadata;
+ }
+
+ @Override
+ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
+ int offset, boolean isBinary) throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Couldn't write to file given its content URI");
+ }
+ @Override
+ public long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
+ throws NoModificationAllowedException {
+ throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
+ }
+
+ protected Cursor openCursorForURL(Uri nativeUri) {
+ ContentResolver contentResolver = context.getContentResolver();
+ try {
+ return contentResolver.query(nativeUri, null, null, null, null);
+ } catch (UnsupportedOperationException e) {
+ return null;
+ }
+ }
+
+ private Long resourceSizeForCursor(Cursor cursor) {
+ int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
+ if (columnIndex != -1) {
+ String sizeStr = cursor.getString(columnIndex);
+ if (sizeStr != null) {
+ return Long.parseLong(sizeStr);
+ }
+ }
+ return null;
+ }
+
+ protected Long lastModifiedDateForCursor(Cursor cursor) {
+ final String[] LOCAL_FILE_PROJECTION = { MediaStore.MediaColumns.DATE_MODIFIED };
+ int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
+ if (columnIndex != -1) {
+ String dateStr = cursor.getString(columnIndex);
+ if (dateStr != null) {
+ return Long.parseLong(dateStr);
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public String filesystemPathForURL(LocalFilesystemURL url) {
+ File f = resourceApi.mapUriToFile(toNativeUri(url));
+ return f == null ? null : f.getAbsolutePath();
+ }
+
+ @Override
+ public LocalFilesystemURL URLforFilesystemPath(String path) {
+ // Returns null as we don't support reverse mapping back to content:// URLs
+ return null;
+ }
+
+ @Override
+ public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
+ return true;
+ }
+}
diff --git a/plugins/cordova-plugin-file/src/android/DirectoryManager.java b/plugins/cordova-plugin-file/src/android/DirectoryManager.java
new file mode 100644
index 0000000..c2d1278
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/DirectoryManager.java
@@ -0,0 +1,133 @@
+/*
+ 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.
+*/
+package org.apache.cordova.file;
+
+import android.os.Environment;
+import android.os.StatFs;
+
+import java.io.File;
+
+/**
+ * This class provides file directory utilities.
+ * All file operations are performed on the SD card.
+ *
+ * It is used by the FileUtils class.
+ */
+public class DirectoryManager {
+
+ @SuppressWarnings("unused")
+ private static final String LOG_TAG = "DirectoryManager";
+
+ /**
+ * Determine if a file or directory exists.
+ * @param name The name of the file to check.
+ * @return T=exists, F=not found
+ */
+ public static boolean testFileExists(String name) {
+ boolean status;
+
+ // If SD card exists
+ if ((testSaveLocationExists()) && (!name.equals(""))) {
+ File path = Environment.getExternalStorageDirectory();
+ File newPath = constructFilePaths(path.toString(), name);
+ status = newPath.exists();
+ }
+ // If no SD card
+ else {
+ status = false;
+ }
+ return status;
+ }
+
+ /**
+ * Get the free disk space
+ *
+ * @return Size in KB or -1 if not available
+ */
+ public static long getFreeDiskSpace(boolean checkInternal) {
+ String status = Environment.getExternalStorageState();
+ long freeSpace = 0;
+
+ // If SD card exists
+ if (status.equals(Environment.MEDIA_MOUNTED)) {
+ freeSpace = freeSpaceCalculation(Environment.getExternalStorageDirectory().getPath());
+ }
+ else if (checkInternal) {
+ freeSpace = freeSpaceCalculation("/");
+ }
+ // If no SD card and we haven't been asked to check the internal directory then return -1
+ else {
+ return -1;
+ }
+
+ return freeSpace;
+ }
+
+ /**
+ * Given a path return the number of free KB
+ *
+ * @param path to the file system
+ * @return free space in KB
+ */
+ private static long freeSpaceCalculation(String path) {
+ StatFs stat = new StatFs(path);
+ long blockSize = stat.getBlockSize();
+ long availableBlocks = stat.getAvailableBlocks();
+ return availableBlocks * blockSize / 1024;
+ }
+
+ /**
+ * Determine if SD card exists.
+ *
+ * @return T=exists, F=not found
+ */
+ public static boolean testSaveLocationExists() {
+ String sDCardStatus = Environment.getExternalStorageState();
+ boolean status;
+
+ // If SD card is mounted
+ if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
+ status = true;
+ }
+
+ // If no SD card
+ else {
+ status = false;
+ }
+ return status;
+ }
+
+ /**
+ * Create a new file object from two file paths.
+ *
+ * @param file1 Base file path
+ * @param file2 Remaining file path
+ * @return File object
+ */
+ private static File constructFilePaths (String file1, String file2) {
+ File newPath;
+ if (file2.startsWith(file1)) {
+ newPath = new File(file2);
+ }
+ else {
+ newPath = new File(file1 + "/" + file2);
+ }
+ return newPath;
+ }
+}
diff --git a/plugins/cordova-plugin-file/src/android/EncodingException.java b/plugins/cordova-plugin-file/src/android/EncodingException.java
new file mode 100644
index 0000000..e9e1653
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/EncodingException.java
@@ -0,0 +1,29 @@
+/*
+ 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.
+*/
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class EncodingException extends Exception {
+
+ public EncodingException(String message) {
+ super(message);
+ }
+
+}
diff --git a/plugins/cordova-plugin-file/src/android/FileExistsException.java b/plugins/cordova-plugin-file/src/android/FileExistsException.java
new file mode 100644
index 0000000..5c4d83d
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/FileExistsException.java
@@ -0,0 +1,29 @@
+/*
+ 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.
+*/
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class FileExistsException extends Exception {
+
+ public FileExistsException(String msg) {
+ super(msg);
+ }
+
+}
diff --git a/plugins/cordova-plugin-file/src/android/FileUtils.java b/plugins/cordova-plugin-file/src/android/FileUtils.java
new file mode 100644
index 0000000..c90a61d
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/FileUtils.java
@@ -0,0 +1,1022 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.app.Activity;
+import android.content.Context;
+import android.net.Uri;
+import android.os.Environment;
+import android.util.Base64;
+import android.util.Log;
+
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaInterface;
+import org.apache.cordova.CordovaPlugin;
+import org.apache.cordova.CordovaWebView;
+import org.apache.cordova.PluginResult;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+
+/**
+ * This class provides file and directory services to JavaScript.
+ */
+public class FileUtils extends CordovaPlugin {
+ private static final String LOG_TAG = "FileUtils";
+
+ public static int NOT_FOUND_ERR = 1;
+ public static int SECURITY_ERR = 2;
+ public static int ABORT_ERR = 3;
+
+ public static int NOT_READABLE_ERR = 4;
+ public static int ENCODING_ERR = 5;
+ public static int NO_MODIFICATION_ALLOWED_ERR = 6;
+ public static int INVALID_STATE_ERR = 7;
+ public static int SYNTAX_ERR = 8;
+ public static int INVALID_MODIFICATION_ERR = 9;
+ public static int QUOTA_EXCEEDED_ERR = 10;
+ public static int TYPE_MISMATCH_ERR = 11;
+ public static int PATH_EXISTS_ERR = 12;
+
+ public static int UNKNOWN_ERR = 1000;
+
+ private boolean configured = false;
+
+ // This field exists only to support getEntry, below, which has been deprecated
+ private static FileUtils filePlugin;
+
+ private interface FileOp {
+ void run(JSONArray args) throws Exception;
+ }
+
+ private ArrayList filesystems;
+
+ public void registerFilesystem(Filesystem fs) {
+ if (fs != null && filesystemForName(fs.name)== null) {
+ this.filesystems.add(fs);
+ }
+ }
+
+ private Filesystem filesystemForName(String name) {
+ for (Filesystem fs:filesystems) {
+ if (fs != null && fs.name != null && fs.name.equals(name)) {
+ return fs;
+ }
+ }
+ return null;
+ }
+
+ protected String[] getExtraFileSystemsPreference(Activity activity) {
+ String fileSystemsStr = preferences.getString("androidextrafilesystems", "files,files-external,documents,sdcard,cache,cache-external,root");
+ return fileSystemsStr.split(",");
+ }
+
+ protected void registerExtraFileSystems(String[] filesystems, HashMap availableFileSystems) {
+ HashSet installedFileSystems = new HashSet();
+
+ /* Register filesystems in order */
+ for (String fsName : filesystems) {
+ if (!installedFileSystems.contains(fsName)) {
+ String fsRoot = availableFileSystems.get(fsName);
+ if (fsRoot != null) {
+ File newRoot = new File(fsRoot);
+ if (newRoot.mkdirs() || newRoot.isDirectory()) {
+ registerFilesystem(new LocalFilesystem(fsName, webView.getContext(), webView.getResourceApi(), newRoot));
+ installedFileSystems.add(fsName);
+ } else {
+ Log.d(LOG_TAG, "Unable to create root dir for filesystem \"" + fsName + "\", skipping");
+ }
+ } else {
+ Log.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName);
+ }
+ }
+ }
+ }
+
+ protected HashMap getAvailableFileSystems(Activity activity) {
+ Context context = activity.getApplicationContext();
+ HashMap availableFileSystems = new HashMap();
+
+ availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
+ availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
+ availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
+ availableFileSystems.put("root", "/");
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ try {
+ availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
+ availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
+ availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
+ }
+ catch(NullPointerException e) {
+ Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
+ }
+ }
+
+ return availableFileSystems;
+ }
+
+ @Override
+ public void initialize(CordovaInterface cordova, CordovaWebView webView) {
+ super.initialize(cordova, webView);
+ this.filesystems = new ArrayList();
+
+ String tempRoot = null;
+ String persistentRoot = null;
+
+ Activity activity = cordova.getActivity();
+ String packageName = activity.getPackageName();
+
+ String location = preferences.getString("androidpersistentfilelocation", "internal");
+
+ tempRoot = activity.getCacheDir().getAbsolutePath();
+ if ("internal".equalsIgnoreCase(location)) {
+ persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
+ this.configured = true;
+ } else if ("compatibility".equalsIgnoreCase(location)) {
+ /*
+ * Fall-back to compatibility mode -- this is the logic implemented in
+ * earlier versions of this plugin, and should be maintained here so
+ * that apps which were originally deployed with older versions of the
+ * plugin can continue to provide access to files stored under those
+ * versions.
+ */
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
+ tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() +
+ "/Android/data/" + packageName + "/cache/";
+ } else {
+ persistentRoot = "/data/data/" + packageName;
+ }
+ this.configured = true;
+ }
+
+ if (this.configured) {
+ // Create the directories if they don't exist.
+ File tmpRootFile = new File(tempRoot);
+ File persistentRootFile = new File(persistentRoot);
+ tmpRootFile.mkdirs();
+ persistentRootFile.mkdirs();
+
+ // Register initial filesystems
+ // Note: The temporary and persistent filesystems need to be the first two
+ // registered, so that they will match window.TEMPORARY and window.PERSISTENT,
+ // per spec.
+ this.registerFilesystem(new LocalFilesystem("temporary", webView.getContext(), webView.getResourceApi(), tmpRootFile));
+ this.registerFilesystem(new LocalFilesystem("persistent", webView.getContext(), webView.getResourceApi(), persistentRootFile));
+ this.registerFilesystem(new ContentFilesystem(webView.getContext(), webView.getResourceApi()));
+ this.registerFilesystem(new AssetFilesystem(webView.getContext().getAssets(), webView.getResourceApi()));
+
+ registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));
+
+ // Initialize static plugin reference for deprecated getEntry method
+ if (filePlugin == null) {
+ FileUtils.filePlugin = this;
+ }
+ } else {
+ Log.e(LOG_TAG, "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
+ activity.finish();
+ }
+ }
+
+ public static FileUtils getFilePlugin() {
+ return filePlugin;
+ }
+
+ private Filesystem filesystemForURL(LocalFilesystemURL localURL) {
+ if (localURL == null) return null;
+ return filesystemForName(localURL.fsName);
+ }
+
+ @Override
+ public Uri remapUri(Uri uri) {
+ // Remap only cdvfile: URLs (not content:).
+ if (!LocalFilesystemURL.FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
+ return null;
+ }
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ return null;
+ }
+ String path = fs.filesystemPathForURL(inputURL);
+ if (path != null) {
+ return Uri.parse("file://" + fs.filesystemPathForURL(inputURL));
+ }
+ return null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ public boolean execute(String action, final String rawArgs, final CallbackContext callbackContext) {
+ if (!configured) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File plugin is not configured. Please see the README.md file for details on how to update config.xml"));
+ return true;
+ }
+ if (action.equals("testSaveLocationExists")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) {
+ boolean b = DirectoryManager.testSaveLocationExists();
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getFreeDiskSpace")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) {
+ long l = DirectoryManager.getFreeDiskSpace(false);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("testFileExists")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException {
+ String fname=args.getString(0);
+ boolean b = DirectoryManager.testFileExists(fname);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("testDirectoryExists")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException {
+ String fname=args.getString(0);
+ boolean b = DirectoryManager.testFileExists(fname);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsText")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ String encoding = args.getString(1);
+ int start = args.getInt(2);
+ int end = args.getInt(3);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsDataURL")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ int start = args.getInt(1);
+ int end = args.getInt(2);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, null, -1);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsArrayBuffer")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ int start = args.getInt(1);
+ int end = args.getInt(2);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readAsBinaryString")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, MalformedURLException {
+ int start = args.getInt(1);
+ int end = args.getInt(2);
+ String fname=args.getString(0);
+ readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("write")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
+ String fname=args.getString(0);
+ String data=args.getString(1);
+ int offset=args.getInt(2);
+ Boolean isBinary=args.getBoolean(3);
+ long fileSize = write(fname, data, offset, isBinary);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("truncate")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, FileNotFoundException, IOException, NoModificationAllowedException {
+ String fname=args.getString(0);
+ int offset=args.getInt(1);
+ long fileSize = truncateFile(fname, offset);
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("requestAllFileSystems")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws IOException, JSONException {
+ callbackContext.success(requestAllFileSystems());
+ }
+ }, rawArgs, callbackContext);
+ } else if (action.equals("requestAllPaths")) {
+ cordova.getThreadPool().execute(
+ new Runnable() {
+ public void run() {
+ try {
+ callbackContext.success(requestAllPaths());
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+ );
+ } else if (action.equals("requestFileSystem")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws IOException, JSONException {
+ int fstype=args.getInt(0);
+ long size = args.optLong(1);
+ if (size != 0 && size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
+ } else {
+ JSONObject obj = requestFileSystem(fstype);
+ callbackContext.success(obj);
+ }
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("resolveLocalFileSystemURI")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws IOException, JSONException {
+ String fname=args.getString(0);
+ JSONObject obj = resolveLocalFileSystemURI(fname);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getFileMetadata")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
+ String fname=args.getString(0);
+ JSONObject obj = getFileMetadata(fname);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getParent")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, IOException {
+ String fname=args.getString(0);
+ JSONObject obj = getParent(fname);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getDirectory")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ String dirname=args.getString(0);
+ String path=args.getString(1);
+ JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("getFile")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ String dirname=args.getString(0);
+ String path=args.getString(1);
+ JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
+ callbackContext.success(obj);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("remove")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, NoModificationAllowedException, InvalidModificationException, MalformedURLException {
+ String fname=args.getString(0);
+ boolean success = remove(fname);
+ if (success) {
+ callbackContext.success();
+ } else {
+ callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
+ }
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("removeRecursively")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, FileExistsException, MalformedURLException, NoModificationAllowedException {
+ String fname=args.getString(0);
+ boolean success = removeRecursively(fname);
+ if (success) {
+ callbackContext.success();
+ } else {
+ callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
+ }
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("moveTo")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
+ String fname=args.getString(0);
+ String newParent=args.getString(1);
+ String newName=args.getString(2);
+ JSONObject entry = transferTo(fname, newParent, newName, true);
+ callbackContext.success(entry);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("copyTo")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
+ String fname=args.getString(0);
+ String newParent=args.getString(1);
+ String newName=args.getString(2);
+ JSONObject entry = transferTo(fname, newParent, newName, false);
+ callbackContext.success(entry);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("readEntries")) {
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
+ String fname=args.getString(0);
+ JSONArray entries = readEntries(fname);
+ callbackContext.success(entries);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else if (action.equals("_getLocalFilesystemPath")) {
+ // Internal method for testing: Get the on-disk location of a local filesystem url.
+ // [Currently used for testing file-transfer]
+ threadhelper( new FileOp( ){
+ public void run(JSONArray args) throws FileNotFoundException, JSONException, MalformedURLException {
+ String localURLstr = args.getString(0);
+ String fname = filesystemPathForURL(localURLstr);
+ callbackContext.success(fname);
+ }
+ }, rawArgs, callbackContext);
+ }
+ else {
+ return false;
+ }
+ return true;
+ }
+
+ public LocalFilesystemURL resolveNativeUri(Uri nativeUri) {
+ LocalFilesystemURL localURL = null;
+
+ // Try all installed filesystems. Return the best matching URL
+ // (determined by the shortest resulting URL)
+ for (Filesystem fs : filesystems) {
+ LocalFilesystemURL url = fs.toLocalUri(nativeUri);
+ if (url != null) {
+ // A shorter fullPath implies that the filesystem is a better
+ // match for the local path than the previous best.
+ if (localURL == null || (url.uri.toString().length() < localURL.toString().length())) {
+ localURL = url;
+ }
+ }
+ }
+ return localURL;
+ }
+
+ /*
+ * These two native-only methods can be used by other plugins to translate between
+ * device file system paths and URLs. By design, there is no direct JavaScript
+ * interface to these methods.
+ */
+
+ public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(localURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.filesystemPathForURL(inputURL);
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ public LocalFilesystemURL filesystemURLforLocalPath(String localPath) {
+ LocalFilesystemURL localURL = null;
+ int shortestFullPath = 0;
+
+ // Try all installed filesystems. Return the best matching URL
+ // (determined by the shortest resulting URL)
+ for (Filesystem fs: filesystems) {
+ LocalFilesystemURL url = fs.URLforFilesystemPath(localPath);
+ if (url != null) {
+ // A shorter fullPath implies that the filesystem is a better
+ // match for the local path than the previous best.
+ if (localURL == null || (url.path.length() < shortestFullPath)) {
+ localURL = url;
+ shortestFullPath = url.path.length();
+ }
+ }
+ }
+ return localURL;
+ }
+
+
+ /* helper to execute functions async and handle the result codes
+ *
+ */
+ private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext){
+ cordova.getThreadPool().execute(new Runnable() {
+ public void run() {
+ try {
+ JSONArray args = new JSONArray(rawArgs);
+ f.run(args);
+ } catch ( Exception e) {
+ if( e instanceof EncodingException){
+ callbackContext.error(FileUtils.ENCODING_ERR);
+ } else if(e instanceof FileNotFoundException) {
+ callbackContext.error(FileUtils.NOT_FOUND_ERR);
+ } else if(e instanceof FileExistsException) {
+ callbackContext.error(FileUtils.PATH_EXISTS_ERR);
+ } else if(e instanceof NoModificationAllowedException ) {
+ callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
+ } else if(e instanceof InvalidModificationException ) {
+ callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
+ } else if(e instanceof MalformedURLException ) {
+ callbackContext.error(FileUtils.ENCODING_ERR);
+ } else if(e instanceof IOException ) {
+ callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
+ } else if(e instanceof EncodingException ) {
+ callbackContext.error(FileUtils.ENCODING_ERR);
+ } else if(e instanceof TypeMismatchException ) {
+ callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
+ } else if(e instanceof JSONException ) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
+ } else {
+ e.printStackTrace();
+ callbackContext.error(FileUtils.UNKNOWN_ERR);
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Allows the user to look up the Entry for a file or directory referred to by a local URI.
+ *
+ * @param uriString of the file/directory to look up
+ * @return a JSONObject representing a Entry from the filesystem
+ * @throws MalformedURLException if the url is not valid
+ * @throws FileNotFoundException if the file does not exist
+ * @throws IOException if the user can't read the file
+ * @throws JSONException
+ */
+ private JSONObject resolveLocalFileSystemURI(String uriString) throws IOException, JSONException {
+ if (uriString == null) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ Uri uri = Uri.parse(uriString);
+
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(uri);
+ if (inputURL == null) {
+ /* Check for file://, content:// urls */
+ inputURL = resolveNativeUri(uri);
+ }
+
+ try {
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ if (fs.exists(inputURL)) {
+ return fs.getEntryForLocalURL(inputURL);
+ }
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ throw new FileNotFoundException();
+ }
+
+ /**
+ * Read the list of files from this directory.
+ *
+ * @return a JSONArray containing JSONObjects that represent Entry objects.
+ * @throws FileNotFoundException if the directory is not found.
+ * @throws JSONException
+ * @throws MalformedURLException
+ */
+ private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.readEntriesAtLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * A setup method that handles the move/copy of files/directories
+ *
+ * @param newName for the file directory to be called, if null use existing file name
+ * @param move if false do a copy, if true do a move
+ * @return a Entry object
+ * @throws NoModificationAllowedException
+ * @throws IOException
+ * @throws InvalidModificationException
+ * @throws EncodingException
+ * @throws JSONException
+ * @throws FileExistsException
+ */
+ private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
+ if (srcURLstr == null || destURLstr == null) {
+ // either no source or no destination provided
+ throw new FileNotFoundException();
+ }
+
+ LocalFilesystemURL srcURL = LocalFilesystemURL.parse(srcURLstr);
+ LocalFilesystemURL destURL = LocalFilesystemURL.parse(destURLstr);
+
+ Filesystem srcFs = this.filesystemForURL(srcURL);
+ Filesystem destFs = this.filesystemForURL(destURL);
+
+ // Check for invalid file name
+ if (newName != null && newName.contains(":")) {
+ throw new EncodingException("Bad file name");
+ }
+
+ return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move);
+ }
+
+ /**
+ * Deletes a directory and all of its contents, if any. In the event of an error
+ * [e.g. trying to delete a directory that contains a file that cannot be removed],
+ * some of the contents of the directory may be deleted.
+ * It is an error to attempt to delete the root directory of a filesystem.
+ *
+ * @return a boolean representing success of failure
+ * @throws FileExistsException
+ * @throws NoModificationAllowedException
+ * @throws MalformedURLException
+ */
+ private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ // You can't delete the root directory.
+ if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
+ throw new NoModificationAllowedException("You can't delete the root directory");
+ }
+
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.recursiveRemoveFileAtLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+
+ /**
+ * Deletes a file or directory. It is an error to attempt to delete a directory that is not empty.
+ * It is an error to attempt to delete the root directory of a filesystem.
+ *
+ * @return a boolean representing success of failure
+ * @throws NoModificationAllowedException
+ * @throws InvalidModificationException
+ * @throws MalformedURLException
+ */
+ private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ // You can't delete the root directory.
+ if ("".equals(inputURL.path) || "/".equals(inputURL.path)) {
+
+ throw new NoModificationAllowedException("You can't delete the root directory");
+ }
+
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.removeFileAtLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * Creates or looks up a file.
+ *
+ * @param baseURLstr base directory
+ * @param path file/directory to lookup or create
+ * @param options specify whether to create or not
+ * @param directory if true look up directory, if false look up file
+ * @return a Entry object
+ * @throws FileExistsException
+ * @throws IOException
+ * @throws TypeMismatchException
+ * @throws EncodingException
+ * @throws JSONException
+ */
+ private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.getFileForLocalURL(inputURL, path, options, directory);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+
+ }
+
+ /**
+ * Look up the parent DirectoryEntry containing this Entry.
+ * If this Entry is the root of its filesystem, its parent is itself.
+ */
+ private JSONObject getParent(String baseURLstr) throws JSONException, IOException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.getParentForLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * Returns a File that represents the current state of the file that this FileEntry represents.
+ *
+ * @return returns a JSONObject represent a W3C File object
+ */
+ private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(baseURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+ return fs.getFileMetadataForLocalURL(inputURL);
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+
+ /**
+ * Requests a filesystem in which to store application data.
+ *
+ * @param type of file system requested
+ * @return a JSONObject representing the file system
+ * @throws IOException
+ * @throws JSONException
+ */
+ private JSONObject requestFileSystem(int type) throws IOException, JSONException {
+ JSONObject fs = new JSONObject();
+ Filesystem rootFs = null;
+ try {
+ rootFs = this.filesystems.get(type);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Pass null through
+ }
+ if (rootFs == null) {
+ throw new IOException("No filesystem of type requested");
+ }
+ fs.put("name", rootFs.name);
+ fs.put("root", rootFs.getRootEntry());
+ return fs;
+ }
+
+
+ /**
+ * Requests a filesystem in which to store application data.
+ *
+ * @return a JSONObject representing the file system
+ */
+ private JSONArray requestAllFileSystems() throws IOException, JSONException {
+ JSONArray ret = new JSONArray();
+ for (Filesystem fs : filesystems) {
+ ret.put(fs.getRootEntry());
+ }
+ return ret;
+ }
+
+ private static String toDirUrl(File f) {
+ return Uri.fromFile(f).toString() + '/';
+ }
+
+ private JSONObject requestAllPaths() throws JSONException {
+ Context context = cordova.getActivity();
+ JSONObject ret = new JSONObject();
+ ret.put("applicationDirectory", "file:///android_asset/");
+ ret.put("applicationStorageDirectory", toDirUrl(context.getFilesDir().getParentFile()));
+ ret.put("dataDirectory", toDirUrl(context.getFilesDir()));
+ ret.put("cacheDirectory", toDirUrl(context.getCacheDir()));
+ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+ try {
+ ret.put("externalApplicationStorageDirectory", toDirUrl(context.getExternalFilesDir(null).getParentFile()));
+ ret.put("externalDataDirectory", toDirUrl(context.getExternalFilesDir(null)));
+ ret.put("externalCacheDirectory", toDirUrl(context.getExternalCacheDir()));
+ ret.put("externalRootDirectory", toDirUrl(Environment.getExternalStorageDirectory()));
+ }
+ catch(NullPointerException e) {
+ /* If external storage is unavailable, context.getExternal* returns null */
+ Log.d(LOG_TAG, "Unable to access these paths, most liklely due to USB storage");
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Returns a JSON object representing the given File. Internal APIs should be modified
+ * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
+ *
+ * @param file the File to convert
+ * @return a JSON representation of the given File
+ * @throws JSONException
+ */
+ public JSONObject getEntryForFile(File file) throws JSONException {
+ JSONObject entry;
+
+ for (Filesystem fs : filesystems) {
+ entry = fs.makeEntryForFile(file);
+ if (entry != null) {
+ return entry;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns a JSON object representing the given File. Deprecated, as this is only used by
+ * FileTransfer, and because it is a static method that should really be an instance method,
+ * since it depends on the actual filesystem roots in use. Internal APIs should be modified
+ * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
+ *
+ * @param file the File to convert
+ * @return a JSON representation of the given File
+ * @throws JSONException
+ */
+ @Deprecated
+ public static JSONObject getEntry(File file) throws JSONException {
+ if (getFilePlugin() != null) {
+ return getFilePlugin().getEntryForFile(file);
+ }
+ return null;
+ }
+
+ /**
+ * Read the contents of a file.
+ * This is done in a background thread; the result is sent to the callback.
+ *
+ * @param start Start position in the file.
+ * @param end End position to stop at (exclusive).
+ * @param callbackContext The context through which to send the result.
+ * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
+ * @param resultType The desired type of data to send to the callback.
+ * @return Contents of file.
+ */
+ public void readFileAs(final String srcURLstr, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) throws MalformedURLException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+
+ fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() {
+ public void handleData(InputStream inputStream, String contentType) {
+ try {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ final int BUFFER_SIZE = 8192;
+ byte[] buffer = new byte[BUFFER_SIZE];
+
+ for (;;) {
+ int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
+
+ if (bytesRead <= 0) {
+ break;
+ }
+ os.write(buffer, 0, bytesRead);
+ }
+
+ PluginResult result;
+ switch (resultType) {
+ case PluginResult.MESSAGE_TYPE_STRING:
+ result = new PluginResult(PluginResult.Status.OK, os.toString(encoding));
+ break;
+ case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
+ result = new PluginResult(PluginResult.Status.OK, os.toByteArray());
+ break;
+ case PluginResult.MESSAGE_TYPE_BINARYSTRING:
+ result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true);
+ break;
+ default: // Base64.
+ byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP);
+ String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
+ result = new PluginResult(PluginResult.Status.OK, s);
+ }
+
+ callbackContext.sendPluginResult(result);
+ } catch (IOException e) {
+ Log.d(LOG_TAG, e.getLocalizedMessage());
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
+ }
+ }
+ });
+
+
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ } catch (FileNotFoundException e) {
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
+ } catch (IOException e) {
+ Log.d(LOG_TAG, e.getLocalizedMessage());
+ callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
+ }
+ }
+
+
+ /**
+ * Write contents of file.
+ *
+ * @param data The contents of the file.
+ * @param offset The position to begin writing the file.
+ * @param isBinary True if the file contents are base64-encoded binary data
+ */
+ /**/
+ public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+
+ long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); Log.d("TEST",srcURLstr + ": "+x); return x;
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+
+ }
+
+ /**
+ * Truncate the file to size
+ */
+ private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
+ try {
+ LocalFilesystemURL inputURL = LocalFilesystemURL.parse(srcURLstr);
+ Filesystem fs = this.filesystemForURL(inputURL);
+ if (fs == null) {
+ throw new MalformedURLException("No installed handlers for this URL");
+ }
+
+ return fs.truncateFileAtURL(inputURL, size);
+ } catch (IllegalArgumentException e) {
+ throw new MalformedURLException("Unrecognized filesystem URL");
+ }
+ }
+}
diff --git a/plugins/cordova-plugin-file/src/android/Filesystem.java b/plugins/cordova-plugin-file/src/android/Filesystem.java
new file mode 100644
index 0000000..faf31d2
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/Filesystem.java
@@ -0,0 +1,325 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.net.Uri;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public abstract class Filesystem {
+
+ protected final Uri rootUri;
+ protected final CordovaResourceApi resourceApi;
+ public final String name;
+ private JSONObject rootEntry;
+
+ public Filesystem(Uri rootUri, String name, CordovaResourceApi resourceApi) {
+ this.rootUri = rootUri;
+ this.name = name;
+ this.resourceApi = resourceApi;
+ }
+
+ public interface ReadFileCallback {
+ public void handleData(InputStream inputStream, String contentType) throws IOException;
+ }
+
+ public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Uri nativeURL) {
+ try {
+ String path = inputURL.path;
+ int end = path.endsWith("/") ? 1 : 0;
+ String[] parts = path.substring(0, path.length() - end).split("/+");
+ String fileName = parts[parts.length - 1];
+
+ JSONObject entry = new JSONObject();
+ entry.put("isFile", !inputURL.isDirectory);
+ entry.put("isDirectory", inputURL.isDirectory);
+ entry.put("name", fileName);
+ entry.put("fullPath", path);
+ // The file system can't be specified, as it would lead to an infinite loop,
+ // but the filesystem name can be.
+ entry.put("filesystemName", inputURL.fsName);
+ // Backwards compatibility
+ entry.put("filesystem", "temporary".equals(inputURL.fsName) ? 0 : 1);
+
+ String nativeUrlStr = nativeURL.toString();
+ if (inputURL.isDirectory && !nativeUrlStr.endsWith("/")) {
+ nativeUrlStr += "/";
+ }
+ entry.put("nativeURL", nativeUrlStr);
+ return entry;
+ } catch (JSONException e) {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+ }
+
+ public JSONObject makeEntryForURL(LocalFilesystemURL inputURL) {
+ Uri nativeUri = toNativeUri(inputURL);
+ return nativeUri == null ? null : makeEntryForURL(inputURL, nativeUri);
+ }
+
+ public JSONObject makeEntryForNativeUri(Uri nativeUri) {
+ LocalFilesystemURL inputUrl = toLocalUri(nativeUri);
+ return inputUrl == null ? null : makeEntryForURL(inputUrl, nativeUri);
+ }
+
+ public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
+ return makeEntryForURL(inputURL);
+ }
+
+ public JSONObject makeEntryForFile(File file) {
+ return makeEntryForNativeUri(Uri.fromFile(file));
+ }
+
+ abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path,
+ JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;
+
+ abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;
+
+ abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;
+
+ abstract LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException;
+
+ public final JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ LocalFilesystemURL[] children = listChildren(inputURL);
+ JSONArray entries = new JSONArray();
+ if (children != null) {
+ for (LocalFilesystemURL url : children) {
+ entries.put(makeEntryForURL(url));
+ }
+ }
+ return entries;
+ }
+
+ abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;
+
+ public Uri getRootUri() {
+ return rootUri;
+ }
+
+ public boolean exists(LocalFilesystemURL inputURL) {
+ try {
+ getFileMetadataForLocalURL(inputURL);
+ } catch (FileNotFoundException e) {
+ return false;
+ }
+ return true;
+ }
+
+ public Uri nativeUriForFullPath(String fullPath) {
+ Uri ret = null;
+ if (fullPath != null) {
+ String encodedPath = Uri.fromFile(new File(fullPath)).getEncodedPath();
+ if (encodedPath.startsWith("/")) {
+ encodedPath = encodedPath.substring(1);
+ }
+ ret = rootUri.buildUpon().appendEncodedPath(encodedPath).build();
+ }
+ return ret;
+ }
+
+ public LocalFilesystemURL localUrlforFullPath(String fullPath) {
+ Uri nativeUri = nativeUriForFullPath(fullPath);
+ if (nativeUri != null) {
+ return toLocalUri(nativeUri);
+ }
+ return null;
+ }
+
+ /**
+ * Removes multiple repeated //s, and collapses processes ../s.
+ */
+ protected static String normalizePath(String rawPath) {
+ // If this is an absolute path, trim the leading "/" and replace it later
+ boolean isAbsolutePath = rawPath.startsWith("/");
+ if (isAbsolutePath) {
+ rawPath = rawPath.replaceFirst("/+", "");
+ }
+ ArrayList components = new ArrayList(Arrays.asList(rawPath.split("/+")));
+ for (int index = 0; index < components.size(); ++index) {
+ if (components.get(index).equals("..")) {
+ components.remove(index);
+ if (index > 0) {
+ components.remove(index-1);
+ --index;
+ }
+ }
+ }
+ StringBuilder normalizedPath = new StringBuilder();
+ for(String component: components) {
+ normalizedPath.append("/");
+ normalizedPath.append(component);
+ }
+ if (isAbsolutePath) {
+ return normalizedPath.toString();
+ } else {
+ return normalizedPath.toString().substring(1);
+ }
+ }
+
+
+
+ public abstract Uri toNativeUri(LocalFilesystemURL inputURL);
+ public abstract LocalFilesystemURL toLocalUri(Uri inputURL);
+
+ public JSONObject getRootEntry() {
+ if (rootEntry == null) {
+ rootEntry = makeEntryForNativeUri(rootUri);
+ }
+ return rootEntry;
+ }
+
+ public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
+ Uri parentUri = inputURL.uri;
+ String parentPath = new File(inputURL.uri.getPath()).getParent();
+ if (!"/".equals(parentPath)) {
+ parentUri = inputURL.uri.buildUpon().path(parentPath + '/').build();
+ }
+ return getEntryForLocalURL(LocalFilesystemURL.parse(parentUri));
+ }
+
+ protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL, boolean isDirectory) {
+ // I know this looks weird but it is to work around a JSON bug.
+ if ("null".equals(newName) || "".equals(newName)) {
+ newName = srcURL.uri.getLastPathSegment();;
+ }
+
+ String newDest = destURL.uri.toString();
+ if (newDest.endsWith("/")) {
+ newDest = newDest + newName;
+ } else {
+ newDest = newDest + "/" + newName;
+ }
+ if (isDirectory) {
+ newDest += '/';
+ }
+ return LocalFilesystemURL.parse(newDest);
+ }
+
+ /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
+ * the destination URL on this filesystem, optionally with a new filename.
+ * If move is true, then this method should either perform an atomic move operation
+ * or remove the source file when finished.
+ */
+ public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
+ Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
+ // First, check to see that we can do it
+ if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
+ throw new NoModificationAllowedException("Cannot move file at source URL");
+ }
+ final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
+
+ Uri srcNativeUri = srcFs.toNativeUri(srcURL);
+
+ CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcNativeUri);
+ OutputStream os = null;
+ try {
+ os = getOutputStreamForURL(destination);
+ } catch (IOException e) {
+ ofrr.inputStream.close();
+ throw e;
+ }
+ // Closes streams.
+ resourceApi.copyResource(ofrr, os);
+
+ if (move) {
+ srcFs.removeFileAtLocalURL(srcURL);
+ }
+ return getEntryForLocalURL(destination);
+ }
+
+ public OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException {
+ return resourceApi.openOutputStream(toNativeUri(inputURL));
+ }
+
+ public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
+ ReadFileCallback readFileCallback) throws IOException {
+ CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(toNativeUri(inputURL));
+ if (end < 0) {
+ end = ofrr.length;
+ }
+ long numBytesToRead = end - start;
+ try {
+ if (start > 0) {
+ ofrr.inputStream.skip(start);
+ }
+ InputStream inputStream = ofrr.inputStream;
+ if (end < ofrr.length) {
+ inputStream = new LimitedInputStream(inputStream, numBytesToRead);
+ }
+ readFileCallback.handleData(inputStream, ofrr.mimeType);
+ } finally {
+ ofrr.inputStream.close();
+ }
+ }
+
+ abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset,
+ boolean isBinary) throws NoModificationAllowedException, IOException;
+
+ abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
+ throws IOException, NoModificationAllowedException;
+
+ // This method should return null if filesystem urls cannot be mapped to paths
+ abstract String filesystemPathForURL(LocalFilesystemURL url);
+
+ abstract LocalFilesystemURL URLforFilesystemPath(String path);
+
+ abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);
+
+ protected class LimitedInputStream extends FilterInputStream {
+ long numBytesToRead;
+ public LimitedInputStream(InputStream in, long numBytesToRead) {
+ super(in);
+ this.numBytesToRead = numBytesToRead;
+ }
+ @Override
+ public int read() throws IOException {
+ if (numBytesToRead <= 0) {
+ return -1;
+ }
+ numBytesToRead--;
+ return in.read();
+ }
+ @Override
+ public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
+ if (numBytesToRead <= 0) {
+ return -1;
+ }
+ int bytesToRead = byteCount;
+ if (byteCount > numBytesToRead) {
+ bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here.
+ }
+ int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
+ numBytesToRead -= numBytesRead;
+ return numBytesRead;
+ }
+ }
+}
diff --git a/plugins/cordova-plugin-file/src/android/InvalidModificationException.java b/plugins/cordova-plugin-file/src/android/InvalidModificationException.java
new file mode 100644
index 0000000..8f6bec5
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/InvalidModificationException.java
@@ -0,0 +1,30 @@
+/*
+ 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.
+*/
+
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class InvalidModificationException extends Exception {
+
+ public InvalidModificationException(String message) {
+ super(message);
+ }
+
+}
diff --git a/plugins/cordova-plugin-file/src/android/LocalFilesystem.java b/plugins/cordova-plugin-file/src/android/LocalFilesystem.java
new file mode 100644
index 0000000..2c77596
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/LocalFilesystem.java
@@ -0,0 +1,505 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+import org.apache.cordova.CordovaResourceApi;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.os.Build;
+import android.os.Environment;
+import android.util.Base64;
+import android.net.Uri;
+import android.content.Context;
+import android.content.Intent;
+
+public class LocalFilesystem extends Filesystem {
+ private final Context context;
+
+ public LocalFilesystem(String name, Context context, CordovaResourceApi resourceApi, File fsRoot) {
+ super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi);
+ this.context = context;
+ }
+
+ public String filesystemPathForFullPath(String fullPath) {
+ return new File(rootUri.getPath(), fullPath).toString();
+ }
+
+ @Override
+ public String filesystemPathForURL(LocalFilesystemURL url) {
+ return filesystemPathForFullPath(url.path);
+ }
+
+ private String fullPathForFilesystemPath(String absolutePath) {
+ if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) {
+ return absolutePath.substring(rootUri.getPath().length() - 1);
+ }
+ return null;
+ }
+
+ @Override
+ public Uri toNativeUri(LocalFilesystemURL inputURL) {
+ return nativeUriForFullPath(inputURL.path);
+ }
+
+ @Override
+ public LocalFilesystemURL toLocalUri(Uri inputURL) {
+ if (!"file".equals(inputURL.getScheme())) {
+ return null;
+ }
+ File f = new File(inputURL.getPath());
+ // Removes and duplicate /s (e.g. file:///a//b/c)
+ Uri resolvedUri = Uri.fromFile(f);
+ String rootUriNoTrailingSlash = rootUri.getEncodedPath();
+ rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
+ if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
+ return null;
+ }
+ String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
+ // Strip leading slash
+ if (!subPath.isEmpty()) {
+ subPath = subPath.substring(1);
+ }
+ Uri.Builder b = new Uri.Builder()
+ .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
+ .authority("localhost")
+ .path(name);
+ if (!subPath.isEmpty()) {
+ b.appendEncodedPath(subPath);
+ }
+ if (f.isDirectory() || inputURL.getPath().endsWith("/")) {
+ // Add trailing / for directories.
+ b.appendEncodedPath("");
+ }
+ return LocalFilesystemURL.parse(b.build());
+ }
+
+ @Override
+ public LocalFilesystemURL URLforFilesystemPath(String path) {
+ return localUrlforFullPath(fullPathForFilesystemPath(path));
+ }
+
+ @Override
+ public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
+ String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
+ boolean create = false;
+ boolean exclusive = false;
+
+ if (options != null) {
+ create = options.optBoolean("create");
+ if (create) {
+ exclusive = options.optBoolean("exclusive");
+ }
+ }
+
+ // Check for a ":" character in the file to line up with BB and iOS
+ if (path.contains(":")) {
+ throw new EncodingException("This path has an invalid \":\" in it.");
+ }
+
+ LocalFilesystemURL requestedURL;
+
+ // Check whether the supplied path is absolute or relative
+ if (directory && !path.endsWith("/")) {
+ path += "/";
+ }
+ if (path.startsWith("/")) {
+ requestedURL = localUrlforFullPath(normalizePath(path));
+ } else {
+ requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
+ }
+
+ File fp = new File(this.filesystemPathForURL(requestedURL));
+
+ if (create) {
+ if (exclusive && fp.exists()) {
+ throw new FileExistsException("create/exclusive fails");
+ }
+ if (directory) {
+ fp.mkdir();
+ } else {
+ fp.createNewFile();
+ }
+ if (!fp.exists()) {
+ throw new FileExistsException("create fails");
+ }
+ }
+ else {
+ if (!fp.exists()) {
+ throw new FileNotFoundException("path does not exist");
+ }
+ if (directory) {
+ if (fp.isFile()) {
+ throw new TypeMismatchException("path doesn't exist or is file");
+ }
+ } else {
+ if (fp.isDirectory()) {
+ throw new TypeMismatchException("path doesn't exist or is directory");
+ }
+ }
+ }
+
+ // Return the directory
+ return makeEntryForURL(requestedURL);
+ }
+
+ @Override
+ public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException {
+
+ File fp = new File(filesystemPathForURL(inputURL));
+
+ // You can't delete a directory that is not empty
+ if (fp.isDirectory() && fp.list().length > 0) {
+ throw new InvalidModificationException("You can't delete a directory that is not empty.");
+ }
+
+ return fp.delete();
+ }
+
+ @Override
+ public boolean exists(LocalFilesystemURL inputURL) {
+ File fp = new File(filesystemPathForURL(inputURL));
+ return fp.exists();
+ }
+
+ @Override
+ public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException {
+ File directory = new File(filesystemPathForURL(inputURL));
+ return removeDirRecursively(directory);
+ }
+
+ protected boolean removeDirRecursively(File directory) throws FileExistsException {
+ if (directory.isDirectory()) {
+ for (File file : directory.listFiles()) {
+ removeDirRecursively(file);
+ }
+ }
+
+ if (!directory.delete()) {
+ throw new FileExistsException("could not delete: " + directory.getName());
+ } else {
+ return true;
+ }
+ }
+
+ @Override
+ public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ File fp = new File(filesystemPathForURL(inputURL));
+
+ if (!fp.exists()) {
+ // The directory we are listing doesn't exist so we should fail.
+ throw new FileNotFoundException();
+ }
+
+ File[] files = fp.listFiles();
+ if (files == null) {
+ // inputURL is a directory
+ return null;
+ }
+ LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
+ for (int i = 0; i < files.length; i++) {
+ entries[i] = URLforFilesystemPath(files[i].getPath());
+ }
+
+ return entries;
+ }
+
+ @Override
+ public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
+ File file = new File(filesystemPathForURL(inputURL));
+
+ if (!file.exists()) {
+ throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
+ }
+
+ JSONObject metadata = new JSONObject();
+ try {
+ // Ensure that directories report a size of 0
+ metadata.put("size", file.isDirectory() ? 0 : file.length());
+ metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file)));
+ metadata.put("name", file.getName());
+ metadata.put("fullPath", inputURL.path);
+ metadata.put("lastModifiedDate", file.lastModified());
+ } catch (JSONException e) {
+ return null;
+ }
+ return metadata;
+ }
+
+ private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException {
+ if (move) {
+ String realSrcPath = srcFs.filesystemPathForURL(srcURL);
+ if (realSrcPath != null) {
+ File srcFile = new File(realSrcPath);
+ if (srcFile.renameTo(destFile)) {
+ return;
+ }
+ // Trying to rename the file failed. Possibly because we moved across file system on the device.
+ }
+ }
+
+ CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL));
+ copyResource(offr, new FileOutputStream(destFile));
+
+ if (move) {
+ srcFs.removeFileAtLocalURL(srcURL);
+ }
+ }
+
+ private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
+ if (move) {
+ String realSrcPath = srcFs.filesystemPathForURL(srcURL);
+ if (realSrcPath != null) {
+ File srcDir = new File(realSrcPath);
+ // If the destination directory already exists and is empty then delete it. This is according to spec.
+ if (dstDir.exists()) {
+ if (dstDir.list().length > 0) {
+ throw new InvalidModificationException("directory is not empty");
+ }
+ dstDir.delete();
+ }
+ // Try to rename the directory
+ if (srcDir.renameTo(dstDir)) {
+ return;
+ }
+ // Trying to rename the file failed. Possibly because we moved across file system on the device.
+ }
+ }
+
+ if (dstDir.exists()) {
+ if (dstDir.list().length > 0) {
+ throw new InvalidModificationException("directory is not empty");
+ }
+ } else {
+ if (!dstDir.mkdir()) {
+ // If we can't create the directory then fail
+ throw new NoModificationAllowedException("Couldn't create the destination directory");
+ }
+ }
+
+ LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
+ for (LocalFilesystemURL childLocalUrl : children) {
+ File target = new File(dstDir, new File(childLocalUrl.path).getName());
+ if (childLocalUrl.isDirectory) {
+ copyDirectory(srcFs, childLocalUrl, target, false);
+ } else {
+ copyFile(srcFs, childLocalUrl, target, false);
+ }
+ }
+
+ if (move) {
+ srcFs.recursiveRemoveFileAtLocalURL(srcURL);
+ }
+ }
+
+ @Override
+ public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
+ Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
+
+ // Check to see if the destination directory exists
+ String newParent = this.filesystemPathForURL(destURL);
+ File destinationDir = new File(newParent);
+ if (!destinationDir.exists()) {
+ // The destination does not exist so we should fail.
+ throw new FileNotFoundException("The source does not exist");
+ }
+
+ // Figure out where we should be copying to
+ final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
+
+ Uri dstNativeUri = toNativeUri(destinationURL);
+ Uri srcNativeUri = srcFs.toNativeUri(srcURL);
+ // Check to see if source and destination are the same file
+ if (dstNativeUri.equals(srcNativeUri)) {
+ throw new InvalidModificationException("Can't copy onto itself");
+ }
+
+ if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
+ throw new InvalidModificationException("Source URL is read-only (cannot move)");
+ }
+
+ File destFile = new File(dstNativeUri.getPath());
+ if (destFile.exists()) {
+ if (!srcURL.isDirectory && destFile.isDirectory()) {
+ throw new InvalidModificationException("Can't copy/move a file to an existing directory");
+ } else if (srcURL.isDirectory && destFile.isFile()) {
+ throw new InvalidModificationException("Can't copy/move a directory to an existing file");
+ }
+ }
+
+ if (srcURL.isDirectory) {
+ // E.g. Copy /sdcard/myDir to /sdcard/myDir/backup
+ if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) {
+ throw new InvalidModificationException("Can't copy directory into itself");
+ }
+ copyDirectory(srcFs, srcURL, destFile, move);
+ } else {
+ copyFile(srcFs, srcURL, destFile, move);
+ }
+ return makeEntryForURL(destinationURL);
+ }
+
+ @Override
+ public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
+ int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
+
+ boolean append = false;
+ if (offset > 0) {
+ this.truncateFileAtURL(inputURL, offset);
+ append = true;
+ }
+
+ byte[] rawData;
+ if (isBinary) {
+ rawData = Base64.decode(data, Base64.DEFAULT);
+ } else {
+ rawData = data.getBytes();
+ }
+ ByteArrayInputStream in = new ByteArrayInputStream(rawData);
+ try
+ {
+ byte buff[] = new byte[rawData.length];
+ String absolutePath = filesystemPathForURL(inputURL);
+ FileOutputStream out = new FileOutputStream(absolutePath, append);
+ try {
+ in.read(buff, 0, buff.length);
+ out.write(buff, 0, rawData.length);
+ out.flush();
+ } finally {
+ // Always close the output
+ out.close();
+ }
+ if (isPublicDirectory(absolutePath)) {
+ broadcastNewFile(Uri.fromFile(new File(absolutePath)));
+ }
+ }
+ catch (NullPointerException e)
+ {
+ // This is a bug in the Android implementation of the Java Stack
+ NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
+ throw realException;
+ }
+
+ return rawData.length;
+ }
+
+ private boolean isPublicDirectory(String absolutePath) {
+ // TODO: should expose a way to scan app's private files (maybe via a flag).
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ // Lollipop has a bug where SD cards are null.
+ for (File f : context.getExternalMediaDirs()) {
+ if(f != null && absolutePath.startsWith(f.getAbsolutePath())) {
+ return true;
+ }
+ }
+ }
+
+ String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
+ return absolutePath.startsWith(extPath);
+ }
+
+ /**
+ * Send broadcast of new file so files appear over MTP
+ */
+ private void broadcastNewFile(Uri nativeUri) {
+ Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri);
+ context.sendBroadcast(intent);
+ }
+
+ @Override
+ public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
+ File file = new File(filesystemPathForURL(inputURL));
+
+ if (!file.exists()) {
+ throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
+ }
+
+ RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
+ try {
+ if (raf.length() >= size) {
+ FileChannel channel = raf.getChannel();
+ channel.truncate(size);
+ return size;
+ }
+
+ return raf.length();
+ } finally {
+ raf.close();
+ }
+
+
+ }
+
+ @Override
+ public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
+ String path = filesystemPathForURL(inputURL);
+ File file = new File(path);
+ return file.exists();
+ }
+
+ // This is a copy & paste from CordovaResource API that is required since CordovaResourceApi
+ // has a bug pre-4.0.0.
+ // TODO: Once cordova-android@4.0.0 is released, delete this copy and make the plugin depend on
+ // 4.0.0 with an engine tag.
+ private static void copyResource(CordovaResourceApi.OpenForReadResult input, OutputStream outputStream) throws IOException {
+ try {
+ InputStream inputStream = input.inputStream;
+ if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
+ FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
+ FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
+ long offset = 0;
+ long length = input.length;
+ if (input.assetFd != null) {
+ offset = input.assetFd.getStartOffset();
+ }
+ // transferFrom()'s 2nd arg is a relative position. Need to set the absolute
+ // position first.
+ inChannel.position(offset);
+ outChannel.transferFrom(inChannel, 0, length);
+ } else {
+ final int BUFFER_SIZE = 8192;
+ byte[] buffer = new byte[BUFFER_SIZE];
+
+ for (;;) {
+ int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
+
+ if (bytesRead <= 0) {
+ break;
+ }
+ outputStream.write(buffer, 0, bytesRead);
+ }
+ }
+ } finally {
+ input.inputStream.close();
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ }
+ }
+}
diff --git a/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java b/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java
new file mode 100644
index 0000000..b96b6ee
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/LocalFilesystemURL.java
@@ -0,0 +1,64 @@
+/*
+ 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.
+ */
+package org.apache.cordova.file;
+
+import android.net.Uri;
+
+public class LocalFilesystemURL {
+
+ public static final String FILESYSTEM_PROTOCOL = "cdvfile";
+
+ public final Uri uri;
+ public final String fsName;
+ public final String path;
+ public final boolean isDirectory;
+
+ private LocalFilesystemURL(Uri uri, String fsName, String fsPath, boolean isDirectory) {
+ this.uri = uri;
+ this.fsName = fsName;
+ this.path = fsPath;
+ this.isDirectory = isDirectory;
+ }
+
+ public static LocalFilesystemURL parse(Uri uri) {
+ if (!FILESYSTEM_PROTOCOL.equals(uri.getScheme())) {
+ return null;
+ }
+ String path = uri.getPath();
+ if (path.length() < 1) {
+ return null;
+ }
+ int firstSlashIdx = path.indexOf('/', 1);
+ if (firstSlashIdx < 0) {
+ return null;
+ }
+ String fsName = path.substring(1, firstSlashIdx);
+ path = path.substring(firstSlashIdx);
+ boolean isDirectory = path.charAt(path.length() - 1) == '/';
+ return new LocalFilesystemURL(uri, fsName, path, isDirectory);
+ }
+
+ public static LocalFilesystemURL parse(String uri) {
+ return parse(Uri.parse(uri));
+ }
+
+ public String toString() {
+ return uri.toString();
+ }
+}
diff --git a/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java b/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java
new file mode 100644
index 0000000..627eafb
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/NoModificationAllowedException.java
@@ -0,0 +1,29 @@
+/*
+ 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.
+*/
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class NoModificationAllowedException extends Exception {
+
+ public NoModificationAllowedException(String message) {
+ super(message);
+ }
+
+}
diff --git a/plugins/cordova-plugin-file/src/android/TypeMismatchException.java b/plugins/cordova-plugin-file/src/android/TypeMismatchException.java
new file mode 100644
index 0000000..1315f9a
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/TypeMismatchException.java
@@ -0,0 +1,30 @@
+/*
+ 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.
+*/
+
+
+package org.apache.cordova.file;
+
+@SuppressWarnings("serial")
+public class TypeMismatchException extends Exception {
+
+ public TypeMismatchException(String message) {
+ super(message);
+ }
+
+}
diff --git a/plugins/cordova-plugin-file/src/android/build-extras.gradle b/plugins/cordova-plugin-file/src/android/build-extras.gradle
new file mode 100644
index 0000000..a0a7844
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/android/build-extras.gradle
@@ -0,0 +1,47 @@
+/*
+ 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.
+ */
+ext.postBuildExtras = {
+ def inAssetsDir = file("assets")
+ def outAssetsDir = inAssetsDir
+ def outFile = new File(outAssetsDir, "cdvasset.manifest")
+
+ def newTask = task("cdvCreateAssetManifest") << {
+ def contents = new HashMap()
+ def sizes = new HashMap()
+ contents[""] = inAssetsDir.list()
+ def tree = fileTree(dir: inAssetsDir)
+ tree.visit { fileDetails ->
+ if (fileDetails.isDirectory()) {
+ contents[fileDetails.relativePath.toString()] = fileDetails.file.list()
+ } else {
+ sizes[fileDetails.relativePath.toString()] = fileDetails.file.length()
+ }
+ }
+
+ outAssetsDir.mkdirs()
+ outFile.withObjectOutputStream { oos ->
+ oos.writeObject(contents)
+ oos.writeObject(sizes)
+ }
+ }
+ newTask.inputs.dir inAssetsDir
+ newTask.outputs.file outFile
+ def preBuildTask = tasks["preBuild"]
+ preBuildTask.dependsOn(newTask)
+}
diff --git a/plugins/cordova-plugin-file/src/blackberry10/index.js b/plugins/cordova-plugin-file/src/blackberry10/index.js
new file mode 100644
index 0000000..913ab30
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/blackberry10/index.js
@@ -0,0 +1,44 @@
+/*
+ *
+ * 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.
+ *
+*/
+module.exports = {
+ setSandbox : function (success, fail, args, env) {
+ require("lib/webview").setSandbox(JSON.parse(decodeURIComponent(args[0])));
+ new PluginResult(args, env).ok();
+ },
+
+ getHomePath: function (success, fail, args, env) {
+ var homeDir = window.qnx.webplatform.getApplication().getEnv("HOME");
+ new PluginResult(args, env).ok(homeDir);
+ },
+
+ requestAllPaths: function (success, fail, args, env) {
+ var homeDir = 'file://' + window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', ''),
+ paths = {
+ applicationDirectory: homeDir + '/app/native/',
+ applicationStorageDirectory: homeDir + '/',
+ dataDirectory: homeDir + '/data/webviews/webfs/persistent/local__0/',
+ cacheDirectory: homeDir + '/data/webviews/webfs/temporary/local__0/',
+ externalRootDirectory: 'file:///accounts/1000/removable/sdcard/',
+ sharedDirectory: homeDir + '/shared/'
+ };
+ success(paths);
+ }
+};
diff --git a/plugins/cordova-plugin-file/src/browser/FileProxy.js b/plugins/cordova-plugin-file/src/browser/FileProxy.js
new file mode 100644
index 0000000..c853db8
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/browser/FileProxy.js
@@ -0,0 +1,964 @@
+/*
+ *
+ * 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.
+ *
+ */
+
+/*global require, exports, module*/
+/*global FILESYSTEM_PREFIX*/
+/*global IDBKeyRange*/
+
+/* Heavily based on https://github.com/ebidel/idb.filesystem.js */
+
+// window.webkitRequestFileSystem and window.webkitResolveLocalFileSystemURL
+// are available only in Chrome and possible a good flag to indicate
+// that we're running in Chrome
+var isChrome = window.webkitRequestFileSystem && window.webkitResolveLocalFileSystemURL;
+
+// For chrome we don't need to implement proxy methods
+// All functionality can be accessed natively.
+if (isChrome) {
+ var pathsPrefix = {
+ // Read-only directory where the application is installed.
+ applicationDirectory: location.origin + "/",
+ // Where to put app-specific data files.
+ dataDirectory: 'filesystem:file:///persistent/',
+ // Cached files that should survive app restarts.
+ // Apps should not rely on the OS to delete files in here.
+ cacheDirectory: 'filesystem:file:///temporary/',
+ };
+
+ exports.requestAllPaths = function(successCallback) {
+ successCallback(pathsPrefix);
+ };
+
+ require("cordova/exec/proxy").add("File", module.exports);
+ return;
+}
+
+var LocalFileSystem = require('./LocalFileSystem'),
+ FileSystem = require('./FileSystem'),
+ FileEntry = require('./FileEntry'),
+ FileError = require('./FileError'),
+ DirectoryEntry = require('./DirectoryEntry'),
+ File = require('./File');
+
+(function(exports, global) {
+ var indexedDB = global.indexedDB || global.mozIndexedDB;
+ if (!indexedDB) {
+ throw "Firefox OS File plugin: indexedDB not supported";
+ }
+
+ var fs_ = null;
+
+ var idb_ = {};
+ idb_.db = null;
+ var FILE_STORE_ = 'entries';
+
+ var DIR_SEPARATOR = '/';
+
+ var pathsPrefix = {
+ // Read-only directory where the application is installed.
+ applicationDirectory: location.origin + "/",
+ // Where to put app-specific data files.
+ dataDirectory: 'file:///persistent/',
+ // Cached files that should survive app restarts.
+ // Apps should not rely on the OS to delete files in here.
+ cacheDirectory: 'file:///temporary/',
+ };
+
+ var unicodeLastChar = 65535;
+
+/*** Exported functionality ***/
+
+ exports.requestFileSystem = function(successCallback, errorCallback, args) {
+ var type = args[0];
+ // Size is ignored since IDB filesystem size depends
+ // on browser implementation and can't be set up by user
+ var size = args[1]; // jshint ignore: line
+
+ if (type !== LocalFileSystem.TEMPORARY && type !== LocalFileSystem.PERSISTENT) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var name = type === LocalFileSystem.TEMPORARY ? 'temporary' : 'persistent';
+ var storageName = (location.protocol + location.host).replace(/:/g, '_');
+
+ var root = new DirectoryEntry('', DIR_SEPARATOR);
+ fs_ = new FileSystem(name, root);
+
+ idb_.open(storageName, function() {
+ successCallback(fs_);
+ }, errorCallback);
+ };
+
+ // Overridden by Android, BlackBerry 10 and iOS to populate fsMap
+ require('./fileSystems').getFs = function(name, callback) {
+ callback(new FileSystem(name, fs_.root));
+ };
+
+ // list a directory's contents (files and folders).
+ exports.readEntries = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+
+ if (typeof successCallback !== 'function') {
+ throw Error('Expected successCallback argument.');
+ }
+
+ var path = resolveToFullPath_(fullPath);
+
+ exports.getDirectory(function() {
+ idb_.getAllEntries(path.fullPath + DIR_SEPARATOR, path.storagePath, function(entries) {
+ successCallback(entries);
+ }, errorCallback);
+ }, function() {
+ if (errorCallback) {
+ errorCallback(FileError.NOT_FOUND_ERR);
+ }
+ }, [path.storagePath, path.fullPath, {create: false}]);
+ };
+
+ exports.getFile = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+ var path = args[1];
+ var options = args[2] || {};
+
+ // Create an absolute path if we were handed a relative one.
+ path = resolveToFullPath_(fullPath, path);
+
+ idb_.get(path.storagePath, function(fileEntry) {
+ if (options.create === true && options.exclusive === true && fileEntry) {
+ // If create and exclusive are both true, and the path already exists,
+ // getFile must fail.
+
+ if (errorCallback) {
+ errorCallback(FileError.PATH_EXISTS_ERR);
+ }
+ } else if (options.create === true && !fileEntry) {
+ // If create is true, the path doesn't exist, and no other error occurs,
+ // getFile must create it as a zero-length file and return a corresponding
+ // FileEntry.
+ var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root));
+
+ newFileEntry.file_ = new MyFile({
+ size: 0,
+ name: newFileEntry.name,
+ lastModifiedDate: new Date(),
+ storagePath: path.storagePath
+ });
+
+ idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback);
+ } else if (options.create === true && fileEntry) {
+ if (fileEntry.isFile) {
+ // Overwrite file, delete then create new.
+ idb_['delete'](path.storagePath, function() {
+ var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root));
+
+ newFileEntry.file_ = new MyFile({
+ size: 0,
+ name: newFileEntry.name,
+ lastModifiedDate: new Date(),
+ storagePath: path.storagePath
+ });
+
+ idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback);
+ }, errorCallback);
+ } else {
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ }
+ } else if ((!options.create || options.create === false) && !fileEntry) {
+ // If create is not true and the path doesn't exist, getFile must fail.
+ if (errorCallback) {
+ errorCallback(FileError.NOT_FOUND_ERR);
+ }
+ } else if ((!options.create || options.create === false) && fileEntry &&
+ fileEntry.isDirectory) {
+ // If create is not true and the path exists, but is a directory, getFile
+ // must fail.
+ if (errorCallback) {
+ errorCallback(FileError.TYPE_MISMATCH_ERR);
+ }
+ } else {
+ // Otherwise, if no other error occurs, getFile must return a FileEntry
+ // corresponding to path.
+
+ successCallback(fileEntryFromIdbEntry(fileEntry));
+ }
+ }, errorCallback);
+ };
+
+ exports.getFileMetadata = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+
+ exports.getFile(function(fileEntry) {
+ successCallback(new File(fileEntry.file_.name, fileEntry.fullPath, '', fileEntry.file_.lastModifiedDate,
+ fileEntry.file_.size));
+ }, errorCallback, [fullPath, null]);
+ };
+
+ exports.getMetadata = function(successCallback, errorCallback, args) {
+ exports.getFile(function (fileEntry) {
+ successCallback(
+ {
+ modificationTime: fileEntry.file_.lastModifiedDate,
+ size: fileEntry.file_.lastModifiedDate
+ });
+ }, errorCallback, args);
+ };
+
+ exports.setMetadata = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+ var metadataObject = args[1];
+
+ exports.getFile(function (fileEntry) {
+ fileEntry.file_.lastModifiedDate = metadataObject.modificationTime;
+ idb_.put(fileEntry, fileEntry.file_.storagePath, successCallback, errorCallback);
+ }, errorCallback, [fullPath, null]);
+ };
+
+ exports.write = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ data = args[1],
+ position = args[2],
+ isBinary = args[3]; // jshint ignore: line
+
+ if (!data) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ if (typeof data === 'string' || data instanceof String) {
+ data = new Blob([data]);
+ }
+
+ exports.getFile(function(fileEntry) {
+ var blob_ = fileEntry.file_.blob_;
+
+ if (!blob_) {
+ blob_ = new Blob([data], {type: data.type});
+ } else {
+ // Calc the head and tail fragments
+ var head = blob_.slice(0, position);
+ var tail = blob_.slice(position + (data.size || data.byteLength));
+
+ // Calc the padding
+ var padding = position - head.size;
+ if (padding < 0) {
+ padding = 0;
+ }
+
+ // Do the "write". In fact, a full overwrite of the Blob.
+ blob_ = new Blob([head, new Uint8Array(padding), data, tail],
+ {type: data.type});
+ }
+
+ // Set the blob we're writing on this file entry so we can recall it later.
+ fileEntry.file_.blob_ = blob_;
+ fileEntry.file_.lastModifiedDate = new Date() || null;
+ fileEntry.file_.size = blob_.size;
+ fileEntry.file_.name = blob_.name;
+ fileEntry.file_.type = blob_.type;
+
+ idb_.put(fileEntry, fileEntry.file_.storagePath, function() {
+ successCallback(data.size || data.byteLength);
+ }, errorCallback);
+ }, errorCallback, [fileName, null]);
+ };
+
+ exports.readAsText = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ enc = args[1],
+ startPos = args[2],
+ endPos = args[3];
+
+ readAs('text', fileName, enc, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.readAsDataURL = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ startPos = args[1],
+ endPos = args[2];
+
+ readAs('dataURL', fileName, null, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.readAsBinaryString = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ startPos = args[1],
+ endPos = args[2];
+
+ readAs('binaryString', fileName, null, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.readAsArrayBuffer = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ startPos = args[1],
+ endPos = args[2];
+
+ readAs('arrayBuffer', fileName, null, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.removeRecursively = exports.remove = function(successCallback, errorCallback, args) {
+ if (typeof successCallback !== 'function') {
+ throw Error('Expected successCallback argument.');
+ }
+
+ var fullPath = resolveToFullPath_(args[0]).storagePath;
+ if (fullPath === pathsPrefix.cacheDirectory || fullPath === pathsPrefix.dataDirectory) {
+ errorCallback(FileError.NO_MODIFICATION_ALLOWED_ERR);
+ return;
+ }
+
+ function deleteEntry(isDirectory) {
+ // TODO: This doesn't protect against directories that have content in it.
+ // Should throw an error instead if the dirEntry is not empty.
+ idb_['delete'](fullPath, function() {
+ successCallback();
+ }, function() {
+ if (errorCallback) { errorCallback(); }
+ }, isDirectory);
+ }
+
+ // We need to to understand what we are deleting:
+ exports.getDirectory(function(entry) {
+ deleteEntry(entry.isDirectory);
+ }, function(){
+ //DirectoryEntry was already deleted or entry is FileEntry
+ deleteEntry(false);
+ }, [fullPath, null, {create: false}]);
+ };
+
+ exports.getDirectory = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+ var path = args[1];
+ var options = args[2];
+
+ // Create an absolute path if we were handed a relative one.
+ path = resolveToFullPath_(fullPath, path);
+
+ idb_.get(path.storagePath, function(folderEntry) {
+ if (!options) {
+ options = {};
+ }
+
+ if (options.create === true && options.exclusive === true && folderEntry) {
+ // If create and exclusive are both true, and the path already exists,
+ // getDirectory must fail.
+ if (errorCallback) {
+ errorCallback(FileError.PATH_EXISTS_ERR);
+ }
+ // There is a strange bug in mobilespec + FF, which results in coming to multiple else-if's
+ // so we are shielding from it with returns.
+ return;
+ }
+
+ if (options.create === true && !folderEntry) {
+ // If create is true, the path doesn't exist, and no other error occurs,
+ // getDirectory must create it as a zero-length file and return a corresponding
+ // MyDirectoryEntry.
+ var dirEntry = new DirectoryEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root));
+
+ idb_.put(dirEntry, path.storagePath, successCallback, errorCallback);
+ return;
+ }
+
+ if (options.create === true && folderEntry) {
+
+ if (folderEntry.isDirectory) {
+ // IDB won't save methods, so we need re-create the MyDirectoryEntry.
+ successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.filesystem));
+ } else {
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ }
+ return;
+ }
+
+ if ((!options.create || options.create === false) && !folderEntry) {
+ // Handle root special. It should always exist.
+ if (path.fullPath === DIR_SEPARATOR) {
+ successCallback(fs_.root);
+ return;
+ }
+
+ // If create is not true and the path doesn't exist, getDirectory must fail.
+ if (errorCallback) {
+ errorCallback(FileError.NOT_FOUND_ERR);
+ }
+
+ return;
+ }
+ if ((!options.create || options.create === false) && folderEntry && folderEntry.isFile) {
+ // If create is not true and the path exists, but is a file, getDirectory
+ // must fail.
+ if (errorCallback) {
+ errorCallback(FileError.TYPE_MISMATCH_ERR);
+ }
+ return;
+ }
+
+ // Otherwise, if no other error occurs, getDirectory must return a
+ // MyDirectoryEntry corresponding to path.
+
+ // IDB won't' save methods, so we need re-create MyDirectoryEntry.
+ successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.filesystem));
+ }, errorCallback);
+ };
+
+ exports.getParent = function(successCallback, errorCallback, args) {
+ if (typeof successCallback !== 'function') {
+ throw Error('Expected successCallback argument.');
+ }
+
+ var fullPath = args[0];
+ //fullPath is like this:
+ //file:///persistent/path/to/file or
+ //file:///persistent/path/to/directory/
+
+ if (fullPath === DIR_SEPARATOR || fullPath === pathsPrefix.cacheDirectory ||
+ fullPath === pathsPrefix.dataDirectory) {
+ successCallback(fs_.root);
+ return;
+ }
+
+ //To delete all slashes at the end
+ while (fullPath[fullPath.length - 1] === '/') {
+ fullPath = fullPath.substr(0, fullPath.length - 1);
+ }
+
+ var pathArr = fullPath.split(DIR_SEPARATOR);
+ pathArr.pop();
+ var parentName = pathArr.pop();
+ var path = pathArr.join(DIR_SEPARATOR) + DIR_SEPARATOR;
+
+ //To get parent of root files
+ var joined = path + parentName + DIR_SEPARATOR;//is like this: file:///persistent/
+ if (joined === pathsPrefix.cacheDirectory || joined === pathsPrefix.dataDirectory) {
+ exports.getDirectory(successCallback, errorCallback, [joined, DIR_SEPARATOR, {create: false}]);
+ return;
+ }
+
+ exports.getDirectory(successCallback, errorCallback, [path, parentName, {create: false}]);
+ };
+
+ exports.copyTo = function(successCallback, errorCallback, args) {
+ var srcPath = args[0];
+ var parentFullPath = args[1];
+ var name = args[2];
+
+ if (name.indexOf('/') !== -1 || srcPath === parentFullPath + name) {
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+
+ return;
+ }
+
+ // Read src file
+ exports.getFile(function(srcFileEntry) {
+
+ var path = resolveToFullPath_(parentFullPath);
+ //Check directory
+ exports.getDirectory(function() {
+
+ // Create dest file
+ exports.getFile(function(dstFileEntry) {
+
+ exports.write(function() {
+ successCallback(dstFileEntry);
+ }, errorCallback, [dstFileEntry.file_.storagePath, srcFileEntry.file_.blob_, 0]);
+
+ }, errorCallback, [parentFullPath, name, {create: true}]);
+
+ }, function() { if (errorCallback) { errorCallback(FileError.NOT_FOUND_ERR); }},
+ [path.storagePath, null, {create:false}]);
+
+ }, errorCallback, [srcPath, null]);
+ };
+
+ exports.moveTo = function(successCallback, errorCallback, args) {
+ var srcPath = args[0];
+ // parentFullPath and name parameters is ignored because
+ // args is being passed downstream to exports.copyTo method
+ var parentFullPath = args[1]; // jshint ignore: line
+ var name = args[2]; // jshint ignore: line
+
+ exports.copyTo(function (fileEntry) {
+
+ exports.remove(function () {
+ successCallback(fileEntry);
+ }, errorCallback, [srcPath]);
+
+ }, errorCallback, args);
+ };
+
+ exports.resolveLocalFileSystemURI = function(successCallback, errorCallback, args) {
+ var path = args[0];
+
+ // Ignore parameters
+ if (path.indexOf('?') !== -1) {
+ path = String(path).split("?")[0];
+ }
+
+ // support for encodeURI
+ if (/\%5/g.test(path) || /\%20/g.test(path)) {
+ path = decodeURI(path);
+ }
+
+ if (path.trim()[0] === '/') {
+ errorCallback && errorCallback(FileError.ENCODING_ERR);
+ return;
+ }
+
+ //support for cdvfile
+ if (path.trim().substr(0,7) === "cdvfile") {
+ if (path.indexOf("cdvfile://localhost") === -1) {
+ errorCallback && errorCallback(FileError.ENCODING_ERR);
+ return;
+ }
+
+ var indexPersistent = path.indexOf("persistent");
+ var indexTemporary = path.indexOf("temporary");
+
+ //cdvfile://localhost/persistent/path/to/file
+ if (indexPersistent !== -1) {
+ path = "file:///persistent" + path.substr(indexPersistent + 10);
+ } else if (indexTemporary !== -1) {
+ path = "file:///temporary" + path.substr(indexTemporary + 9);
+ } else {
+ errorCallback && errorCallback(FileError.ENCODING_ERR);
+ return;
+ }
+ }
+
+ // to avoid path form of '///path/to/file'
+ function handlePathSlashes(path) {
+ var cutIndex = 0;
+ for (var i = 0; i < path.length - 1; i++) {
+ if (path[i] === DIR_SEPARATOR && path[i + 1] === DIR_SEPARATOR) {
+ cutIndex = i + 1;
+ } else break;
+ }
+
+ return path.substr(cutIndex);
+ }
+
+ // Handle localhost containing paths (see specs )
+ if (path.indexOf('file://localhost/') === 0) {
+ path = path.replace('file://localhost/', 'file:///');
+ }
+
+ if (path.indexOf(pathsPrefix.dataDirectory) === 0) {
+ path = path.substring(pathsPrefix.dataDirectory.length - 1);
+ path = handlePathSlashes(path);
+
+ exports.requestFileSystem(function() {
+ exports.getFile(successCallback, function() {
+ exports.getDirectory(successCallback, errorCallback, [pathsPrefix.dataDirectory, path,
+ {create: false}]);
+ }, [pathsPrefix.dataDirectory, path, {create: false}]);
+ }, errorCallback, [LocalFileSystem.PERSISTENT]);
+ } else if (path.indexOf(pathsPrefix.cacheDirectory) === 0) {
+ path = path.substring(pathsPrefix.cacheDirectory.length - 1);
+ path = handlePathSlashes(path);
+
+ exports.requestFileSystem(function() {
+ exports.getFile(successCallback, function() {
+ exports.getDirectory(successCallback, errorCallback, [pathsPrefix.cacheDirectory, path,
+ {create: false}]);
+ }, [pathsPrefix.cacheDirectory, path, {create: false}]);
+ }, errorCallback, [LocalFileSystem.TEMPORARY]);
+ } else if (path.indexOf(pathsPrefix.applicationDirectory) === 0) {
+ path = path.substring(pathsPrefix.applicationDirectory.length);
+ //TODO: need to cut out redundant slashes?
+
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", path, true);
+ xhr.onreadystatechange = function () {
+ if (xhr.status === 200 && xhr.readyState === 4) {
+ exports.requestFileSystem(function(fs) {
+ fs.name = location.hostname;
+
+ //TODO: need to call exports.getFile(...) to handle errors correct
+ fs.root.getFile(path, {create: true}, writeFile, errorCallback);
+ }, errorCallback, [LocalFileSystem.PERSISTENT]);
+ }
+ };
+
+ xhr.onerror = function () {
+ errorCallback && errorCallback(FileError.NOT_READABLE_ERR);
+ };
+
+ xhr.send();
+ } else {
+ errorCallback && errorCallback(FileError.NOT_FOUND_ERR);
+ }
+
+ function writeFile(entry) {
+ entry.createWriter(function (fileWriter) {
+ fileWriter.onwriteend = function (evt) {
+ if (!evt.target.error) {
+ entry.filesystemName = location.hostname;
+ successCallback(entry);
+ }
+ };
+ fileWriter.onerror = function () {
+ errorCallback && errorCallback(FileError.NOT_READABLE_ERR);
+ };
+ fileWriter.write(new Blob([xhr.response]));
+ }, errorCallback);
+ }
+ };
+
+ exports.requestAllPaths = function(successCallback) {
+ successCallback(pathsPrefix);
+ };
+
+/*** Helpers ***/
+
+ /**
+ * Interface to wrap the native File interface.
+ *
+ * This interface is necessary for creating zero-length (empty) files,
+ * something the Filesystem API allows you to do. Unfortunately, File's
+ * constructor cannot be called directly, making it impossible to instantiate
+ * an empty File in JS.
+ *
+ * @param {Object} opts Initial values.
+ * @constructor
+ */
+ function MyFile(opts) {
+ var blob_ = new Blob();
+
+ this.size = opts.size || 0;
+ this.name = opts.name || '';
+ this.type = opts.type || '';
+ this.lastModifiedDate = opts.lastModifiedDate || null;
+ this.storagePath = opts.storagePath || '';
+
+ // Need some black magic to correct the object's size/name/type based on the
+ // blob that is saved.
+ Object.defineProperty(this, 'blob_', {
+ enumerable: true,
+ get: function() {
+ return blob_;
+ },
+ set: function(val) {
+ blob_ = val;
+ this.size = blob_.size;
+ this.name = blob_.name;
+ this.type = blob_.type;
+ this.lastModifiedDate = blob_.lastModifiedDate;
+ }.bind(this)
+ });
+ }
+
+ MyFile.prototype.constructor = MyFile;
+
+ // When saving an entry, the fullPath should always lead with a slash and never
+ // end with one (e.g. a directory). Also, resolve '.' and '..' to an absolute
+ // one. This method ensures path is legit!
+ function resolveToFullPath_(cwdFullPath, path) {
+ path = path || '';
+ var fullPath = path;
+ var prefix = '';
+
+ cwdFullPath = cwdFullPath || DIR_SEPARATOR;
+ if (cwdFullPath.indexOf(FILESYSTEM_PREFIX) === 0) {
+ prefix = cwdFullPath.substring(0, cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length));
+ cwdFullPath = cwdFullPath.substring(cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length));
+ }
+
+ var relativePath = path[0] !== DIR_SEPARATOR;
+ if (relativePath) {
+ fullPath = cwdFullPath;
+ if (cwdFullPath !== DIR_SEPARATOR) {
+ fullPath += DIR_SEPARATOR + path;
+ } else {
+ fullPath += path;
+ }
+ }
+
+ // Remove doubled separator substrings
+ var re = new RegExp(DIR_SEPARATOR + DIR_SEPARATOR, 'g');
+ fullPath = fullPath.replace(re, DIR_SEPARATOR);
+
+ // Adjust '..'s by removing parent directories when '..' flows in path.
+ var parts = fullPath.split(DIR_SEPARATOR);
+ for (var i = 0; i < parts.length; ++i) {
+ var part = parts[i];
+ if (part === '..') {
+ parts[i - 1] = '';
+ parts[i] = '';
+ }
+ }
+ fullPath = parts.filter(function(el) {
+ return el;
+ }).join(DIR_SEPARATOR);
+
+ // Add back in leading slash.
+ if (fullPath[0] !== DIR_SEPARATOR) {
+ fullPath = DIR_SEPARATOR + fullPath;
+ }
+
+ // Replace './' by current dir. ('./one/./two' -> one/two)
+ fullPath = fullPath.replace(/\.\//g, DIR_SEPARATOR);
+
+ // Replace '//' with '/'.
+ fullPath = fullPath.replace(/\/\//g, DIR_SEPARATOR);
+
+ // Replace '/.' with '/'.
+ fullPath = fullPath.replace(/\/\./g, DIR_SEPARATOR);
+
+ // Remove '/' if it appears on the end.
+ if (fullPath[fullPath.length - 1] === DIR_SEPARATOR &&
+ fullPath !== DIR_SEPARATOR) {
+ fullPath = fullPath.substring(0, fullPath.length - 1);
+ }
+
+ var storagePath = prefix + fullPath;
+ storagePath = decodeURI(storagePath);
+ fullPath = decodeURI(fullPath);
+
+ return {
+ storagePath: storagePath,
+ fullPath: fullPath,
+ fileName: fullPath.split(DIR_SEPARATOR).pop(),
+ fsName: prefix.split(DIR_SEPARATOR).pop()
+ };
+ }
+
+ function fileEntryFromIdbEntry(fileEntry) {
+ // IDB won't save methods, so we need re-create the FileEntry.
+ var clonedFileEntry = new FileEntry(fileEntry.name, fileEntry.fullPath, fileEntry.filesystem);
+ clonedFileEntry.file_ = fileEntry.file_;
+
+ return clonedFileEntry;
+ }
+
+ function readAs(what, fullPath, encoding, startPos, endPos, successCallback, errorCallback) {
+ exports.getFile(function(fileEntry) {
+ var fileReader = new FileReader(),
+ blob = fileEntry.file_.blob_.slice(startPos, endPos);
+
+ fileReader.onload = function(e) {
+ successCallback(e.target.result);
+ };
+
+ fileReader.onerror = errorCallback;
+
+ switch (what) {
+ case 'text':
+ fileReader.readAsText(blob, encoding);
+ break;
+ case 'dataURL':
+ fileReader.readAsDataURL(blob);
+ break;
+ case 'arrayBuffer':
+ fileReader.readAsArrayBuffer(blob);
+ break;
+ case 'binaryString':
+ fileReader.readAsBinaryString(blob);
+ break;
+ }
+
+ }, errorCallback, [fullPath, null]);
+ }
+
+/*** Core logic to handle IDB operations ***/
+
+ idb_.open = function(dbName, successCallback, errorCallback) {
+ var self = this;
+
+ // TODO: FF 12.0a1 isn't liking a db name with : in it.
+ var request = indexedDB.open(dbName.replace(':', '_')/*, 1 /*version*/);
+
+ request.onerror = errorCallback || onError;
+
+ request.onupgradeneeded = function(e) {
+ // First open was called or higher db version was used.
+
+ // console.log('onupgradeneeded: oldVersion:' + e.oldVersion,
+ // 'newVersion:' + e.newVersion);
+
+ self.db = e.target.result;
+ self.db.onerror = onError;
+
+ if (!self.db.objectStoreNames.contains(FILE_STORE_)) {
+ self.db.createObjectStore(FILE_STORE_/*,{keyPath: 'id', autoIncrement: true}*/);
+ }
+ };
+
+ request.onsuccess = function(e) {
+ self.db = e.target.result;
+ self.db.onerror = onError;
+ successCallback(e);
+ };
+
+ request.onblocked = errorCallback || onError;
+ };
+
+ idb_.close = function() {
+ this.db.close();
+ this.db = null;
+ };
+
+ idb_.get = function(fullPath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var tx = this.db.transaction([FILE_STORE_], 'readonly');
+
+ var request = tx.objectStore(FILE_STORE_).get(fullPath);
+
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function() {
+ successCallback(request.result);
+ };
+ };
+
+ idb_.getAllEntries = function(fullPath, storagePath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var results = [];
+
+ if (storagePath[storagePath.length - 1] === DIR_SEPARATOR) {
+ storagePath = storagePath.substring(0, storagePath.length - 1);
+ }
+
+ var range = IDBKeyRange.bound(storagePath + DIR_SEPARATOR + ' ',
+ storagePath + DIR_SEPARATOR + String.fromCharCode(unicodeLastChar));
+
+ var tx = this.db.transaction([FILE_STORE_], 'readonly');
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function() {
+ results = results.filter(function(val) {
+ var pathWithoutSlash = val.fullPath;
+
+ if (val.fullPath[val.fullPath.length - 1] === DIR_SEPARATOR) {
+ pathWithoutSlash = pathWithoutSlash.substr(0, pathWithoutSlash.length - 1);
+ }
+
+ var valPartsLen = pathWithoutSlash.split(DIR_SEPARATOR).length;
+ var fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length;
+
+ /* Input fullPath parameter equals '//' for root folder */
+ /* Entries in root folder has valPartsLen equals 2 (see below) */
+ if (fullPath[fullPath.length -1] === DIR_SEPARATOR && fullPath.trim().length === 2) {
+ fullPathPartsLen = 1;
+ } else if (fullPath[fullPath.length -1] === DIR_SEPARATOR) {
+ fullPathPartsLen = fullPath.substr(0, fullPath.length - 1).split(DIR_SEPARATOR).length;
+ } else {
+ fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length;
+ }
+
+ if (valPartsLen === fullPathPartsLen + 1) {
+ // If this a subfolder and entry is a direct child, include it in
+ // the results. Otherwise, it's not an entry of this folder.
+ return val;
+ } else return false;
+ });
+
+ successCallback(results);
+ };
+
+ var request = tx.objectStore(FILE_STORE_).openCursor(range);
+
+ request.onsuccess = function(e) {
+ var cursor = e.target.result;
+ if (cursor) {
+ var val = cursor.value;
+
+ results.push(val.isFile ? fileEntryFromIdbEntry(val) : new DirectoryEntry(val.name, val.fullPath, val.filesystem));
+ cursor['continue']();
+ }
+ };
+ };
+
+ idb_['delete'] = function(fullPath, successCallback, errorCallback, isDirectory) {
+ if (!idb_.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var tx = this.db.transaction([FILE_STORE_], 'readwrite');
+ tx.oncomplete = successCallback;
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function() {
+ if (isDirectory) {
+ //We delete nested files and folders after deleting parent folder
+ //We use ranges: https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange
+ fullPath = fullPath + DIR_SEPARATOR;
+
+ //Range contains all entries in the form fullPath where
+ //symbol in the range from ' ' to symbol which has code `unicodeLastChar`
+ var range = IDBKeyRange.bound(fullPath + ' ', fullPath + String.fromCharCode(unicodeLastChar));
+
+ var newTx = this.db.transaction([FILE_STORE_], 'readwrite');
+ newTx.oncomplete = successCallback;
+ newTx.onabort = errorCallback || onError;
+ newTx.objectStore(FILE_STORE_)['delete'](range);
+ } else {
+ successCallback();
+ }
+ };
+ tx.objectStore(FILE_STORE_)['delete'](fullPath);
+ };
+
+ idb_.put = function(entry, storagePath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var tx = this.db.transaction([FILE_STORE_], 'readwrite');
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function() {
+ // TODO: Error is thrown if we pass the request event back instead.
+ successCallback(entry);
+ };
+
+ tx.objectStore(FILE_STORE_).put(entry, storagePath);
+ };
+
+ // Global error handler. Errors bubble from request, to transaction, to db.
+ function onError(e) {
+ switch (e.target.errorCode) {
+ case 12:
+ console.log('Error - Attempt to open db with a lower version than the ' +
+ 'current one.');
+ break;
+ default:
+ console.log('errorCode: ' + e.target.errorCode);
+ }
+
+ console.log(e, e.code, e.message);
+ }
+
+})(module.exports, window);
+
+require("cordova/exec/proxy").add("File", module.exports);
diff --git a/plugins/cordova-plugin-file/src/firefoxos/FileProxy.js b/plugins/cordova-plugin-file/src/firefoxos/FileProxy.js
new file mode 100644
index 0000000..3662edc
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/firefoxos/FileProxy.js
@@ -0,0 +1,785 @@
+/*
+ *
+ * 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.
+ *
+ */
+
+var LocalFileSystem = require('./LocalFileSystem'),
+ FileSystem = require('./FileSystem'),
+ FileEntry = require('./FileEntry'),
+ FileError = require('./FileError'),
+ DirectoryEntry = require('./DirectoryEntry'),
+ File = require('./File');
+
+/*
+QUIRKS:
+ Does not fail when removing non-empty directories
+ Does not support metadata for directories
+ Does not support requestAllFileSystems
+ Does not support resolveLocalFileSystemURI
+ Methods copyTo and moveTo do not support directories
+
+ Heavily based on https://github.com/ebidel/idb.filesystem.js
+ */
+
+
+(function(exports, global) {
+ var indexedDB = global.indexedDB || global.mozIndexedDB;
+ if (!indexedDB) {
+ throw "Firefox OS File plugin: indexedDB not supported";
+ }
+
+ var fs_ = null;
+
+ var idb_ = {};
+ idb_.db = null;
+ var FILE_STORE_ = 'entries';
+
+ var DIR_SEPARATOR = '/';
+ var DIR_OPEN_BOUND = String.fromCharCode(DIR_SEPARATOR.charCodeAt(0) + 1);
+
+ var pathsPrefix = {
+ // Read-only directory where the application is installed.
+ applicationDirectory: location.origin + "/",
+ // Where to put app-specific data files.
+ dataDirectory: 'file:///persistent/',
+ // Cached files that should survive app restarts.
+ // Apps should not rely on the OS to delete files in here.
+ cacheDirectory: 'file:///temporary/',
+ };
+
+/*** Exported functionality ***/
+
+ exports.requestFileSystem = function(successCallback, errorCallback, args) {
+ var type = args[0];
+ var size = args[1];
+
+ if (type !== LocalFileSystem.TEMPORARY && type !== LocalFileSystem.PERSISTENT) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var name = type === LocalFileSystem.TEMPORARY ? 'temporary' : 'persistent';
+ var storageName = (location.protocol + location.host).replace(/:/g, '_');
+
+ var root = new DirectoryEntry('', DIR_SEPARATOR);
+ fs_ = new FileSystem(name, root);
+
+ idb_.open(storageName, function() {
+ successCallback(fs_);
+ }, errorCallback);
+ };
+
+ require('./fileSystems').getFs = function(name, callback) {
+ callback(new FileSystem(name, fs_.root));
+ };
+
+ // list a directory's contents (files and folders).
+ exports.readEntries = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+
+ if (!successCallback) {
+ throw Error('Expected successCallback argument.');
+ }
+
+ var path = resolveToFullPath_(fullPath);
+
+ idb_.getAllEntries(path.fullPath, path.storagePath, function(entries) {
+ successCallback(entries);
+ }, errorCallback);
+ };
+
+ exports.getFile = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+ var path = args[1];
+ var options = args[2] || {};
+
+ // Create an absolute path if we were handed a relative one.
+ path = resolveToFullPath_(fullPath, path);
+
+ idb_.get(path.storagePath, function(fileEntry) {
+ if (options.create === true && options.exclusive === true && fileEntry) {
+ // If create and exclusive are both true, and the path already exists,
+ // getFile must fail.
+
+ if (errorCallback) {
+ errorCallback(FileError.PATH_EXISTS_ERR);
+ }
+ } else if (options.create === true && !fileEntry) {
+ // If create is true, the path doesn't exist, and no other error occurs,
+ // getFile must create it as a zero-length file and return a corresponding
+ // FileEntry.
+ var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root));
+
+ newFileEntry.file_ = new MyFile({
+ size: 0,
+ name: newFileEntry.name,
+ lastModifiedDate: new Date(),
+ storagePath: path.storagePath
+ });
+
+ idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback);
+ } else if (options.create === true && fileEntry) {
+ if (fileEntry.isFile) {
+ // Overwrite file, delete then create new.
+ idb_['delete'](path.storagePath, function() {
+ var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root));
+
+ newFileEntry.file_ = new MyFile({
+ size: 0,
+ name: newFileEntry.name,
+ lastModifiedDate: new Date(),
+ storagePath: path.storagePath
+ });
+
+ idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback);
+ }, errorCallback);
+ } else {
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ }
+ } else if ((!options.create || options.create === false) && !fileEntry) {
+ // If create is not true and the path doesn't exist, getFile must fail.
+ if (errorCallback) {
+ errorCallback(FileError.NOT_FOUND_ERR);
+ }
+ } else if ((!options.create || options.create === false) && fileEntry &&
+ fileEntry.isDirectory) {
+ // If create is not true and the path exists, but is a directory, getFile
+ // must fail.
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ } else {
+ // Otherwise, if no other error occurs, getFile must return a FileEntry
+ // corresponding to path.
+
+ successCallback(fileEntryFromIdbEntry(fileEntry));
+ }
+ }, errorCallback);
+ };
+
+ exports.getFileMetadata = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+
+ exports.getFile(function(fileEntry) {
+ successCallback(new File(fileEntry.file_.name, fileEntry.fullPath, '', fileEntry.file_.lastModifiedDate,
+ fileEntry.file_.size));
+ }, errorCallback, [fullPath, null]);
+ };
+
+ exports.getMetadata = function(successCallback, errorCallback, args) {
+ exports.getFile(function (fileEntry) {
+ successCallback(
+ {
+ modificationTime: fileEntry.file_.lastModifiedDate,
+ size: fileEntry.file_.lastModifiedDate
+ });
+ }, errorCallback, args);
+ };
+
+ exports.setMetadata = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+ var metadataObject = args[1];
+
+ exports.getFile(function (fileEntry) {
+ fileEntry.file_.lastModifiedDate = metadataObject.modificationTime;
+ }, errorCallback, [fullPath, null]);
+ };
+
+ exports.write = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ data = args[1],
+ position = args[2],
+ isBinary = args[3];
+
+ if (!data) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ exports.getFile(function(fileEntry) {
+ var blob_ = fileEntry.file_.blob_;
+
+ if (!blob_) {
+ blob_ = new Blob([data], {type: data.type});
+ } else {
+ // Calc the head and tail fragments
+ var head = blob_.slice(0, position);
+ var tail = blob_.slice(position + data.byteLength);
+
+ // Calc the padding
+ var padding = position - head.size;
+ if (padding < 0) {
+ padding = 0;
+ }
+
+ // Do the "write". In fact, a full overwrite of the Blob.
+ blob_ = new Blob([head, new Uint8Array(padding), data, tail],
+ {type: data.type});
+ }
+
+ // Set the blob we're writing on this file entry so we can recall it later.
+ fileEntry.file_.blob_ = blob_;
+ fileEntry.file_.lastModifiedDate = data.lastModifiedDate || null;
+ fileEntry.file_.size = blob_.size;
+ fileEntry.file_.name = blob_.name;
+ fileEntry.file_.type = blob_.type;
+
+ idb_.put(fileEntry, fileEntry.file_.storagePath, function() {
+ successCallback(data.byteLength);
+ }, errorCallback);
+ }, errorCallback, [fileName, null]);
+ };
+
+ exports.readAsText = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ enc = args[1],
+ startPos = args[2],
+ endPos = args[3];
+
+ readAs('text', fileName, enc, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.readAsDataURL = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ startPos = args[1],
+ endPos = args[2];
+
+ readAs('dataURL', fileName, null, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.readAsBinaryString = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ startPos = args[1],
+ endPos = args[2];
+
+ readAs('binaryString', fileName, null, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.readAsArrayBuffer = function(successCallback, errorCallback, args) {
+ var fileName = args[0],
+ startPos = args[1],
+ endPos = args[2];
+
+ readAs('arrayBuffer', fileName, null, startPos, endPos, successCallback, errorCallback);
+ };
+
+ exports.removeRecursively = exports.remove = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+
+ // TODO: This doesn't protect against directories that have content in it.
+ // Should throw an error instead if the dirEntry is not empty.
+ idb_['delete'](fullPath, function() {
+ successCallback();
+ }, errorCallback);
+ };
+
+ exports.getDirectory = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+ var path = args[1];
+ var options = args[2];
+
+ // Create an absolute path if we were handed a relative one.
+ path = resolveToFullPath_(fullPath, path);
+
+ idb_.get(path.storagePath, function(folderEntry) {
+ if (!options) {
+ options = {};
+ }
+
+ if (options.create === true && options.exclusive === true && folderEntry) {
+ // If create and exclusive are both true, and the path already exists,
+ // getDirectory must fail.
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ } else if (options.create === true && !folderEntry) {
+ // If create is true, the path doesn't exist, and no other error occurs,
+ // getDirectory must create it as a zero-length file and return a corresponding
+ // MyDirectoryEntry.
+ var dirEntry = new DirectoryEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root));
+
+ idb_.put(dirEntry, path.storagePath, successCallback, errorCallback);
+ } else if (options.create === true && folderEntry) {
+
+ if (folderEntry.isDirectory) {
+ // IDB won't save methods, so we need re-create the MyDirectoryEntry.
+ successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.fileSystem));
+ } else {
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ }
+ } else if ((!options.create || options.create === false) && !folderEntry) {
+ // Handle root special. It should always exist.
+ if (path.fullPath === DIR_SEPARATOR) {
+ successCallback(fs_.root);
+ return;
+ }
+
+ // If create is not true and the path doesn't exist, getDirectory must fail.
+ if (errorCallback) {
+ errorCallback(FileError.NOT_FOUND_ERR);
+ }
+ } else if ((!options.create || options.create === false) && folderEntry &&
+ folderEntry.isFile) {
+ // If create is not true and the path exists, but is a file, getDirectory
+ // must fail.
+ if (errorCallback) {
+ errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ }
+ } else {
+ // Otherwise, if no other error occurs, getDirectory must return a
+ // MyDirectoryEntry corresponding to path.
+
+ // IDB won't' save methods, so we need re-create MyDirectoryEntry.
+ successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.fileSystem));
+ }
+ }, errorCallback);
+ };
+
+ exports.getParent = function(successCallback, errorCallback, args) {
+ var fullPath = args[0];
+
+ if (fullPath === DIR_SEPARATOR) {
+ successCallback(fs_.root);
+ return;
+ }
+
+ var pathArr = fullPath.split(DIR_SEPARATOR);
+ pathArr.pop();
+ var namesa = pathArr.pop();
+ var path = pathArr.join(DIR_SEPARATOR);
+
+ exports.getDirectory(successCallback, errorCallback, [path, namesa, {create: false}]);
+ };
+
+ exports.copyTo = function(successCallback, errorCallback, args) {
+ var srcPath = args[0];
+ var parentFullPath = args[1];
+ var name = args[2];
+
+ // Read src file
+ exports.getFile(function(srcFileEntry) {
+
+ // Create dest file
+ exports.getFile(function(dstFileEntry) {
+
+ exports.write(function() {
+ successCallback(dstFileEntry);
+ }, errorCallback, [dstFileEntry.file_.storagePath, srcFileEntry.file_.blob_, 0]);
+
+ }, errorCallback, [parentFullPath, name, {create: true}]);
+
+ }, errorCallback, [srcPath, null]);
+ };
+
+ exports.moveTo = function(successCallback, errorCallback, args) {
+ var srcPath = args[0];
+ var parentFullPath = args[1];
+ var name = args[2];
+
+ exports.copyTo(function (fileEntry) {
+
+ exports.remove(function () {
+ successCallback(fileEntry);
+ }, errorCallback, [srcPath]);
+
+ }, errorCallback, args);
+ };
+
+ exports.resolveLocalFileSystemURI = function(successCallback, errorCallback, args) {
+ var path = args[0];
+
+ // Ignore parameters
+ if (path.indexOf('?') !== -1) {
+ path = String(path).split("?")[0];
+ }
+
+ // support for encodeURI
+ if (/\%5/g.test(path)) {
+ path = decodeURI(path);
+ }
+
+ if (path.indexOf(pathsPrefix.dataDirectory) === 0) {
+ path = path.substring(pathsPrefix.dataDirectory.length - 1);
+
+ exports.requestFileSystem(function(fs) {
+ fs.root.getFile(path, {create: false}, successCallback, function() {
+ fs.root.getDirectory(path, {create: false}, successCallback, errorCallback);
+ });
+ }, errorCallback, [LocalFileSystem.PERSISTENT]);
+ } else if (path.indexOf(pathsPrefix.cacheDirectory) === 0) {
+ path = path.substring(pathsPrefix.cacheDirectory.length - 1);
+
+ exports.requestFileSystem(function(fs) {
+ fs.root.getFile(path, {create: false}, successCallback, function() {
+ fs.root.getDirectory(path, {create: false}, successCallback, errorCallback);
+ });
+ }, errorCallback, [LocalFileSystem.TEMPORARY]);
+ } else if (path.indexOf(pathsPrefix.applicationDirectory) === 0) {
+ path = path.substring(pathsPrefix.applicationDirectory.length);
+
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", path, true);
+ xhr.onreadystatechange = function () {
+ if (xhr.status === 200 && xhr.readyState === 4) {
+ exports.requestFileSystem(function(fs) {
+ fs.name = location.hostname;
+ fs.root.getFile(path, {create: true}, writeFile, errorCallback);
+ }, errorCallback, [LocalFileSystem.PERSISTENT]);
+ }
+ };
+
+ xhr.onerror = function () {
+ errorCallback && errorCallback(FileError.NOT_READABLE_ERR);
+ };
+
+ xhr.send();
+ } else {
+ errorCallback && errorCallback(FileError.NOT_FOUND_ERR);
+ }
+
+ function writeFile(entry) {
+ entry.createWriter(function (fileWriter) {
+ fileWriter.onwriteend = function (evt) {
+ if (!evt.target.error) {
+ entry.filesystemName = location.hostname;
+ successCallback(entry);
+ }
+ };
+ fileWriter.onerror = function () {
+ errorCallback && errorCallback(FileError.NOT_READABLE_ERR);
+ };
+ fileWriter.write(new Blob([xhr.response]));
+ }, errorCallback);
+ }
+ };
+
+ exports.requestAllPaths = function(successCallback) {
+ successCallback(pathsPrefix);
+ };
+
+/*** Helpers ***/
+
+ /**
+ * Interface to wrap the native File interface.
+ *
+ * This interface is necessary for creating zero-length (empty) files,
+ * something the Filesystem API allows you to do. Unfortunately, File's
+ * constructor cannot be called directly, making it impossible to instantiate
+ * an empty File in JS.
+ *
+ * @param {Object} opts Initial values.
+ * @constructor
+ */
+ function MyFile(opts) {
+ var blob_ = new Blob();
+
+ this.size = opts.size || 0;
+ this.name = opts.name || '';
+ this.type = opts.type || '';
+ this.lastModifiedDate = opts.lastModifiedDate || null;
+ this.storagePath = opts.storagePath || '';
+
+ // Need some black magic to correct the object's size/name/type based on the
+ // blob that is saved.
+ Object.defineProperty(this, 'blob_', {
+ enumerable: true,
+ get: function() {
+ return blob_;
+ },
+ set: function(val) {
+ blob_ = val;
+ this.size = blob_.size;
+ this.name = blob_.name;
+ this.type = blob_.type;
+ this.lastModifiedDate = blob_.lastModifiedDate;
+ }.bind(this)
+ });
+ }
+
+ MyFile.prototype.constructor = MyFile;
+
+ // When saving an entry, the fullPath should always lead with a slash and never
+ // end with one (e.g. a directory). Also, resolve '.' and '..' to an absolute
+ // one. This method ensures path is legit!
+ function resolveToFullPath_(cwdFullPath, path) {
+ path = path || '';
+ var fullPath = path;
+ var prefix = '';
+
+ cwdFullPath = cwdFullPath || DIR_SEPARATOR;
+ if (cwdFullPath.indexOf(FILESYSTEM_PREFIX) === 0) {
+ prefix = cwdFullPath.substring(0, cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length));
+ cwdFullPath = cwdFullPath.substring(cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length));
+ }
+
+ var relativePath = path[0] !== DIR_SEPARATOR;
+ if (relativePath) {
+ fullPath = cwdFullPath;
+ if (cwdFullPath != DIR_SEPARATOR) {
+ fullPath += DIR_SEPARATOR + path;
+ } else {
+ fullPath += path;
+ }
+ }
+
+ // Adjust '..'s by removing parent directories when '..' flows in path.
+ var parts = fullPath.split(DIR_SEPARATOR);
+ for (var i = 0; i < parts.length; ++i) {
+ var part = parts[i];
+ if (part == '..') {
+ parts[i - 1] = '';
+ parts[i] = '';
+ }
+ }
+ fullPath = parts.filter(function(el) {
+ return el;
+ }).join(DIR_SEPARATOR);
+
+ // Add back in leading slash.
+ if (fullPath[0] !== DIR_SEPARATOR) {
+ fullPath = DIR_SEPARATOR + fullPath;
+ }
+
+ // Replace './' by current dir. ('./one/./two' -> one/two)
+ fullPath = fullPath.replace(/\.\//g, DIR_SEPARATOR);
+
+ // Replace '//' with '/'.
+ fullPath = fullPath.replace(/\/\//g, DIR_SEPARATOR);
+
+ // Replace '/.' with '/'.
+ fullPath = fullPath.replace(/\/\./g, DIR_SEPARATOR);
+
+ // Remove '/' if it appears on the end.
+ if (fullPath[fullPath.length - 1] == DIR_SEPARATOR &&
+ fullPath != DIR_SEPARATOR) {
+ fullPath = fullPath.substring(0, fullPath.length - 1);
+ }
+
+ return {
+ storagePath: prefix + fullPath,
+ fullPath: fullPath,
+ fileName: fullPath.split(DIR_SEPARATOR).pop(),
+ fsName: prefix.split(DIR_SEPARATOR).pop()
+ };
+ }
+
+ function fileEntryFromIdbEntry(fileEntry) {
+ // IDB won't save methods, so we need re-create the FileEntry.
+ var clonedFileEntry = new FileEntry(fileEntry.name, fileEntry.fullPath, fileEntry.fileSystem);
+ clonedFileEntry.file_ = fileEntry.file_;
+
+ return clonedFileEntry;
+ }
+
+ function readAs(what, fullPath, encoding, startPos, endPos, successCallback, errorCallback) {
+ exports.getFile(function(fileEntry) {
+ var fileReader = new FileReader(),
+ blob = fileEntry.file_.blob_.slice(startPos, endPos);
+
+ fileReader.onload = function(e) {
+ successCallback(e.target.result);
+ };
+
+ fileReader.onerror = errorCallback;
+
+ switch (what) {
+ case 'text':
+ fileReader.readAsText(blob, encoding);
+ break;
+ case 'dataURL':
+ fileReader.readAsDataURL(blob);
+ break;
+ case 'arrayBuffer':
+ fileReader.readAsArrayBuffer(blob);
+ break;
+ case 'binaryString':
+ fileReader.readAsBinaryString(blob);
+ break;
+ }
+
+ }, errorCallback, [fullPath, null]);
+ }
+
+/*** Core logic to handle IDB operations ***/
+
+ idb_.open = function(dbName, successCallback, errorCallback) {
+ var self = this;
+
+ // TODO: FF 12.0a1 isn't liking a db name with : in it.
+ var request = indexedDB.open(dbName.replace(':', '_')/*, 1 /*version*/);
+
+ request.onerror = errorCallback || onError;
+
+ request.onupgradeneeded = function(e) {
+ // First open was called or higher db version was used.
+
+ // console.log('onupgradeneeded: oldVersion:' + e.oldVersion,
+ // 'newVersion:' + e.newVersion);
+
+ self.db = e.target.result;
+ self.db.onerror = onError;
+
+ if (!self.db.objectStoreNames.contains(FILE_STORE_)) {
+ var store = self.db.createObjectStore(FILE_STORE_/*,{keyPath: 'id', autoIncrement: true}*/);
+ }
+ };
+
+ request.onsuccess = function(e) {
+ self.db = e.target.result;
+ self.db.onerror = onError;
+ successCallback(e);
+ };
+
+ request.onblocked = errorCallback || onError;
+ };
+
+ idb_.close = function() {
+ this.db.close();
+ this.db = null;
+ };
+
+ idb_.get = function(fullPath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var tx = this.db.transaction([FILE_STORE_], 'readonly');
+
+ //var request = tx.objectStore(FILE_STORE_).get(fullPath);
+ var range = IDBKeyRange.bound(fullPath, fullPath + DIR_OPEN_BOUND,
+ false, true);
+ var request = tx.objectStore(FILE_STORE_).get(range);
+
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function(e) {
+ successCallback(request.result);
+ };
+ };
+
+ idb_.getAllEntries = function(fullPath, storagePath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var results = [];
+
+ if (storagePath[storagePath.length - 1] === DIR_SEPARATOR) {
+ storagePath = storagePath.substring(0, storagePath.length - 1);
+ }
+
+ range = IDBKeyRange.bound(
+ storagePath + DIR_SEPARATOR, storagePath + DIR_OPEN_BOUND, false, true);
+
+ var tx = this.db.transaction([FILE_STORE_], 'readonly');
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function(e) {
+ results = results.filter(function(val) {
+ var valPartsLen = val.fullPath.split(DIR_SEPARATOR).length;
+ var fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length;
+
+ if (fullPath === DIR_SEPARATOR && valPartsLen < fullPathPartsLen + 1) {
+ // Hack to filter out entries in the root folder. This is inefficient
+ // because reading the entires of fs.root (e.g. '/') returns ALL
+ // results in the database, then filters out the entries not in '/'.
+ return val;
+ } else if (fullPath !== DIR_SEPARATOR &&
+ valPartsLen === fullPathPartsLen + 1) {
+ // If this a subfolder and entry is a direct child, include it in
+ // the results. Otherwise, it's not an entry of this folder.
+ return val;
+ }
+ });
+
+ successCallback(results);
+ };
+
+ var request = tx.objectStore(FILE_STORE_).openCursor(range);
+
+ request.onsuccess = function(e) {
+ var cursor = e.target.result;
+ if (cursor) {
+ var val = cursor.value;
+
+ results.push(val.isFile ? fileEntryFromIdbEntry(val) : new DirectoryEntry(val.name, val.fullPath, val.fileSystem));
+ cursor['continue']();
+ }
+ };
+ };
+
+ idb_['delete'] = function(fullPath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var tx = this.db.transaction([FILE_STORE_], 'readwrite');
+ tx.oncomplete = successCallback;
+ tx.onabort = errorCallback || onError;
+
+ //var request = tx.objectStore(FILE_STORE_).delete(fullPath);
+ var range = IDBKeyRange.bound(
+ fullPath, fullPath + DIR_OPEN_BOUND, false, true);
+ tx.objectStore(FILE_STORE_)['delete'](range);
+ };
+
+ idb_.put = function(entry, storagePath, successCallback, errorCallback) {
+ if (!this.db) {
+ errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR);
+ return;
+ }
+
+ var tx = this.db.transaction([FILE_STORE_], 'readwrite');
+ tx.onabort = errorCallback || onError;
+ tx.oncomplete = function(e) {
+ // TODO: Error is thrown if we pass the request event back instead.
+ successCallback(entry);
+ };
+
+ tx.objectStore(FILE_STORE_).put(entry, storagePath);
+ };
+
+ // Global error handler. Errors bubble from request, to transaction, to db.
+ function onError(e) {
+ switch (e.target.errorCode) {
+ case 12:
+ console.log('Error - Attempt to open db with a lower version than the ' +
+ 'current one.');
+ break;
+ default:
+ console.log('errorCode: ' + e.target.errorCode);
+ }
+
+ console.log(e, e.code, e.message);
+ }
+
+// Clean up.
+// TODO: Is there a place for this?
+// global.addEventListener('beforeunload', function(e) {
+// idb_.db && idb_.db.close();
+// }, false);
+
+})(module.exports, window);
+
+require("cordova/exec/proxy").add("File", module.exports);
diff --git a/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h
new file mode 100644
index 0000000..e09e225
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.h
@@ -0,0 +1,30 @@
+/*
+ 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.
+ */
+
+#import "CDVFile.h"
+
+extern NSString* const kCDVAssetsLibraryPrefix;
+extern NSString* const kCDVAssetsLibraryScheme;
+
+@interface CDVAssetLibraryFilesystem : NSObject {
+}
+
+- (id) initWithName:(NSString *)name;
+
+@end
diff --git a/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m
new file mode 100644
index 0000000..0b95fac
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ios/CDVAssetLibraryFilesystem.m
@@ -0,0 +1,253 @@
+/*
+ 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.
+ */
+
+#import "CDVFile.h"
+#import "CDVAssetLibraryFilesystem.h"
+#import
+#import
+#import
+#import
+#import
+
+NSString* const kCDVAssetsLibraryPrefix = @"assets-library://";
+NSString* const kCDVAssetsLibraryScheme = @"assets-library";
+
+@implementation CDVAssetLibraryFilesystem
+@synthesize name=_name, urlTransformer;
+
+
+/*
+ The CDVAssetLibraryFilesystem works with resources which are identified
+ by iOS as
+ asset-library://
+ and represents them internally as URLs of the form
+ cdvfile://localhost/assets-library/
+ */
+
+- (NSURL *)assetLibraryURLForLocalURL:(CDVFilesystemURL *)url
+{
+ if ([url.url.scheme isEqualToString:kCDVFilesystemURLPrefix]) {
+ NSString *path = [[url.url absoluteString] substringFromIndex:[@"cdvfile://localhost/assets-library" length]];
+ return [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@", path]];
+ }
+ return url.url;
+}
+
+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
+{
+ NSDictionary* entry = [self makeEntryForLocalURL:url];
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
+}
+
+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
+ return [self makeEntryForPath:url.fullPath isDirectory:NO];
+}
+
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir
+{
+ NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
+ NSString* lastPart = [fullPath lastPathComponent];
+ if (isDir && ![fullPath hasSuffix:@"/"]) {
+ fullPath = [fullPath stringByAppendingString:@"/"];
+ }
+ [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
+ [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
+ [dirEntry setObject:fullPath forKey:@"fullPath"];
+ [dirEntry setObject:lastPart forKey:@"name"];
+ [dirEntry setObject:self.name forKey: @"filesystemName"];
+
+ NSURL* nativeURL = [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@",fullPath]];
+ if (self.urlTransformer) {
+ nativeURL = self.urlTransformer(nativeURL);
+ }
+ dirEntry[@"nativeURL"] = [nativeURL absoluteString];
+
+ return dirEntry;
+}
+
+/* helper function to get the mimeType from the file extension
+ * IN:
+ * NSString* fullPath - filename (may include path)
+ * OUT:
+ * NSString* the mime type as type/subtype. nil if not able to determine
+ */
++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath
+{
+ NSString* mimeType = nil;
+
+ if (fullPath) {
+ CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
+ if (typeId) {
+ mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
+ if (!mimeType) {
+ // special case for m4a
+ if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
+ mimeType = @"audio/mp4";
+ } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
+ mimeType = @"audio/wav";
+ } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
+ mimeType = @"text/css";
+ }
+ }
+ CFRelease(typeId);
+ }
+ }
+ return mimeType;
+}
+
+- (id)initWithName:(NSString *)name
+{
+ if (self) {
+ _name = name;
+ }
+ return self;
+}
+
+- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
+{
+ // return unsupported result for assets-library URLs
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"getFile not supported for assets-library URLs."];
+}
+
+- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
+{
+ // we don't (yet?) support getting the parent of an asset
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_READABLE_ERR];
+}
+
+- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
+{
+ // setMetadata doesn't make sense for asset library files
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
+}
+
+- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
+{
+ // return error for assets-library URLs
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
+}
+
+- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
+{
+ // return error for assets-library URLs
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"removeRecursively not supported for assets-library URLs."];
+}
+
+- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
+{
+ // return unsupported result for assets-library URLs
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"readEntries not supported for assets-library URLs."];
+}
+
+- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
+{
+ // assets-library files can't be truncated
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
+}
+
+- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
+{
+ // text can't be written into assets-library files
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
+}
+
+- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
+{
+ // Copying to an assets library file is not doable, since we can't write it.
+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
+ callback(result);
+}
+
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
+{
+ NSString *path = nil;
+ if ([[url.url scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
+ path = [url.url path];
+ } else {
+ path = url.fullPath;
+ }
+ if ([path hasSuffix:@"/"]) {
+ path = [path substringToIndex:([path length]-1)];
+ }
+ return path;
+}
+
+- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
+{
+ ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
+ if (asset) {
+ // We have the asset! Get the data and send it off.
+ ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
+ NSUInteger size = (end > start) ? (end - start) : [assetRepresentation size];
+ Byte* buffer = (Byte*)malloc(size);
+ NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:start length:size error:nil];
+ NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];
+ NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);
+
+ callback(data, MIMEType, NO_ERROR);
+ } else {
+ callback(nil, nil, NOT_FOUND_ERR);
+ }
+ };
+
+ ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
+ // Retrieving the asset failed for some reason. Send the appropriate error.
+ NSLog(@"Error: %@", error);
+ callback(nil, nil, SECURITY_ERR);
+ };
+
+ ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
+ [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
+}
+
+- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
+{
+ // In this case, we need to use an asynchronous method to retrieve the file.
+ // Because of this, we can't just assign to `result` and send it at the end of the method.
+ // Instead, we return after calling the asynchronous method and send `result` in each of the blocks.
+ ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
+ if (asset) {
+ // We have the asset! Populate the dictionary and send it off.
+ NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
+ ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
+ [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[assetRepresentation size]] forKey:@"size"];
+ [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
+ NSString* filename = [assetRepresentation filename];
+ [fileInfo setObject:filename forKey:@"name"];
+ [fileInfo setObject:[CDVAssetLibraryFilesystem getMimeTypeFromPath:filename] forKey:@"type"];
+ NSDate* creationDate = [asset valueForProperty:ALAssetPropertyDate];
+ NSNumber* msDate = [NSNumber numberWithDouble:[creationDate timeIntervalSince1970] * 1000];
+ [fileInfo setObject:msDate forKey:@"lastModifiedDate"];
+
+ callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]);
+ } else {
+ // We couldn't find the asset. Send the appropriate error.
+ callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]);
+ }
+ };
+ ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
+ // Retrieving the asset failed for some reason. Send the appropriate error.
+ callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]);
+ };
+
+ ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
+ [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
+ return;
+}
+@end
diff --git a/plugins/cordova-plugin-file/src/ios/CDVFile.h b/plugins/cordova-plugin-file/src/ios/CDVFile.h
new file mode 100644
index 0000000..33630c0
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ios/CDVFile.h
@@ -0,0 +1,157 @@
+/*
+ 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.
+ */
+
+#import
+#import
+
+NSString* const kCDVAssetsLibraryPrefix;
+NSString* const kCDVFilesystemURLPrefix;
+
+enum CDVFileError {
+ NO_ERROR = 0,
+ NOT_FOUND_ERR = 1,
+ SECURITY_ERR = 2,
+ ABORT_ERR = 3,
+ NOT_READABLE_ERR = 4,
+ ENCODING_ERR = 5,
+ NO_MODIFICATION_ALLOWED_ERR = 6,
+ INVALID_STATE_ERR = 7,
+ SYNTAX_ERR = 8,
+ INVALID_MODIFICATION_ERR = 9,
+ QUOTA_EXCEEDED_ERR = 10,
+ TYPE_MISMATCH_ERR = 11,
+ PATH_EXISTS_ERR = 12
+};
+typedef int CDVFileError;
+
+@interface CDVFilesystemURL : NSObject {
+ NSURL *_url;
+ NSString *_fileSystemName;
+ NSString *_fullPath;
+}
+
+- (id) initWithString:(NSString*)strURL;
+- (id) initWithURL:(NSURL*)URL;
++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL;
++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL;
+
+- (NSString *)absoluteURL;
+
+@property (atomic) NSURL *url;
+@property (atomic) NSString *fileSystemName;
+@property (atomic) NSString *fullPath;
+
+@end
+
+@interface CDVFilesystemURLProtocol : NSURLProtocol
+@end
+
+@protocol CDVFileSystem
+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url;
+- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options;
+- (CDVPluginResult *)getParentForURL:(CDVFilesystemURL *)localURI;
+- (CDVPluginResult *)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options;
+- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI;
+- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI;
+- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI;
+- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos;
+- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend;
+- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback;
+- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback;
+- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback;
+
+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url;
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir;
+
+@property (nonatomic,strong) NSString *name;
+@property (nonatomic, copy) NSURL*(^urlTransformer)(NSURL*);
+
+@optional
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURI;
+- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path;
+
+@end
+
+@interface CDVFile : CDVPlugin {
+ NSString* rootDocsPath;
+ NSString* appDocsPath;
+ NSString* appLibraryPath;
+ NSString* appTempPath;
+
+ NSMutableArray* fileSystems_;
+ BOOL userHasAllowed;
+}
+
+- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath;
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir;
+- (NSDictionary *)makeEntryForURL:(NSURL *)URL;
+- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath;
+
+- (NSObject *)filesystemForURL:(CDVFilesystemURL *)localURL;
+
+/* Native Registration API */
+- (void)registerFilesystem:(NSObject *)fs;
+- (NSObject *)fileSystemByName:(NSString *)fsName;
+
+/* Exec API */
+- (void)requestFileSystem:(CDVInvokedUrlCommand*)command;
+- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command;
+- (void)getDirectory:(CDVInvokedUrlCommand*)command;
+- (void)getFile:(CDVInvokedUrlCommand*)command;
+- (void)getParent:(CDVInvokedUrlCommand*)command;
+- (void)removeRecursively:(CDVInvokedUrlCommand*)command;
+- (void)remove:(CDVInvokedUrlCommand*)command;
+- (void)copyTo:(CDVInvokedUrlCommand*)command;
+- (void)moveTo:(CDVInvokedUrlCommand*)command;
+- (void)getFileMetadata:(CDVInvokedUrlCommand*)command;
+- (void)readEntries:(CDVInvokedUrlCommand*)command;
+- (void)readAsText:(CDVInvokedUrlCommand*)command;
+- (void)readAsDataURL:(CDVInvokedUrlCommand*)command;
+- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command;
+- (void)write:(CDVInvokedUrlCommand*)command;
+- (void)testFileExists:(CDVInvokedUrlCommand*)command;
+- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command;
+- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command;
+- (void)truncate:(CDVInvokedUrlCommand*)command;
+- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy;
+
+/* Compatibilty with older File API */
+- (NSString*)getMimeTypeFromPath:(NSString*)fullPath;
+- (NSDictionary *)getDirectoryEntry:(NSString *)target isDirectory:(BOOL)bDirRequest;
+
+/* Conversion between filesystem paths and URLs */
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)URL;
+
+/* Internal methods for testing */
+- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command;
+
+@property (nonatomic, strong) NSString* rootDocsPath;
+@property (nonatomic, strong) NSString* appDocsPath;
+@property (nonatomic, strong) NSString* appLibraryPath;
+@property (nonatomic, strong) NSString* appTempPath;
+@property (nonatomic, strong) NSString* persistentPath;
+@property (nonatomic, strong) NSString* temporaryPath;
+@property (nonatomic, strong) NSMutableArray* fileSystems;
+
+@property BOOL userHasAllowed;
+
+@end
+
+#define kW3FileTemporary @"temporary"
+#define kW3FilePersistent @"persistent"
diff --git a/plugins/cordova-plugin-file/src/ios/CDVFile.m b/plugins/cordova-plugin-file/src/ios/CDVFile.m
new file mode 100644
index 0000000..9b3bb38
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ios/CDVFile.m
@@ -0,0 +1,1106 @@
+/*
+ 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.
+ */
+
+#import
+#import "CDVFile.h"
+#import "CDVLocalFilesystem.h"
+#import "CDVAssetLibraryFilesystem.h"
+#import
+
+static NSString* toBase64(NSData* data) {
+ SEL s1 = NSSelectorFromString(@"cdv_base64EncodedString");
+ SEL s2 = NSSelectorFromString(@"base64EncodedString");
+ SEL s3 = NSSelectorFromString(@"base64EncodedStringWithOptions:");
+
+ if ([data respondsToSelector:s1]) {
+ NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s1];
+ return func(data, s1);
+ } else if ([data respondsToSelector:s2]) {
+ NSString* (*func)(id, SEL) = (void *)[data methodForSelector:s2];
+ return func(data, s2);
+ } else if ([data respondsToSelector:s3]) {
+ NSString* (*func)(id, SEL, NSUInteger) = (void *)[data methodForSelector:s3];
+ return func(data, s3, 0);
+ } else {
+ return nil;
+ }
+}
+
+CDVFile *filePlugin = nil;
+
+extern NSString * const NSURLIsExcludedFromBackupKey __attribute__((weak_import));
+
+#ifndef __IPHONE_5_1
+ NSString* const NSURLIsExcludedFromBackupKey = @"NSURLIsExcludedFromBackupKey";
+#endif
+
+NSString* const kCDVFilesystemURLPrefix = @"cdvfile";
+
+@implementation CDVFilesystemURL
+@synthesize url=_url;
+@synthesize fileSystemName=_fileSystemName;
+@synthesize fullPath=_fullPath;
+
+- (id) initWithString:(NSString *)strURL
+{
+ if ( self = [super init] ) {
+ NSURL *decodedURL = [NSURL URLWithString:strURL];
+ return [self initWithURL:decodedURL];
+ }
+ return nil;
+}
+
+-(id) initWithURL:(NSURL *)URL
+{
+ if ( self = [super init] ) {
+ _url = URL;
+ _fileSystemName = [self filesystemNameForLocalURI:URL];
+ _fullPath = [self fullPathForLocalURI:URL];
+ }
+ return self;
+}
+
+/*
+ * IN
+ * NSString localURI
+ * OUT
+ * NSString FileSystem Name for this URI, or nil if it is not recognized.
+ */
+- (NSString *)filesystemNameForLocalURI:(NSURL *)uri
+{
+ if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) {
+ NSArray *pathComponents = [uri pathComponents];
+ if (pathComponents != nil && pathComponents.count > 1) {
+ return [pathComponents objectAtIndex:1];
+ }
+ } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
+ return @"assets-library";
+ }
+ return nil;
+}
+
+/*
+ * IN
+ * NSString localURI
+ * OUT
+ * NSString fullPath component suitable for an Entry object.
+ * The incoming URI should be properly escaped. The returned fullPath is unescaped.
+ */
+- (NSString *)fullPathForLocalURI:(NSURL *)uri
+{
+ if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) {
+ NSString *path = [uri path];
+ if ([uri query]) {
+ path = [NSString stringWithFormat:@"%@?%@", path, [uri query]];
+ }
+ NSRange slashRange = [path rangeOfString:@"/" options:0 range:NSMakeRange(1, path.length-1)];
+ if (slashRange.location == NSNotFound) {
+ return @"";
+ }
+ return [path substringFromIndex:slashRange.location];
+ } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
+ return [[uri absoluteString] substringFromIndex:[kCDVAssetsLibraryScheme length]+2];
+ }
+ return nil;
+}
+
++ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL
+{
+ return [[CDVFilesystemURL alloc] initWithString:strURL];
+}
+
++ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL
+{
+ return [[CDVFilesystemURL alloc] initWithURL:URL];
+}
+
+- (NSString *)absoluteURL
+{
+ return [NSString stringWithFormat:@"cdvfile://localhost/%@%@", self.fileSystemName, self.fullPath];
+}
+
+@end
+
+@implementation CDVFilesystemURLProtocol
+
++ (BOOL)canInitWithRequest:(NSURLRequest*)request
+{
+ NSURL* url = [request URL];
+ return [[url scheme] isEqualToString:kCDVFilesystemURLPrefix];
+}
+
++ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request
+{
+ return request;
+}
+
++ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB
+{
+ return [[[requestA URL] resourceSpecifier] isEqualToString:[[requestB URL] resourceSpecifier]];
+}
+
+- (void)startLoading
+{
+ CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithURL:[[self request] URL]];
+ NSObject *fs = [filePlugin filesystemForURL:url];
+ [fs readFileAtURL:url start:0 end:-1 callback:^void(NSData *data, NSString *mimetype, CDVFileError error) {
+ NSMutableDictionary* responseHeaders = [[NSMutableDictionary alloc] init];
+ responseHeaders[@"Cache-Control"] = @"no-cache";
+
+ if (!error) {
+ responseHeaders[@"Content-Type"] = mimetype;
+ NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:200 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders];
+ [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
+ [[self client] URLProtocol:self didLoadData:data];
+ [[self client] URLProtocolDidFinishLoading:self];
+ } else {
+ NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:404 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders];
+ [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
+ [[self client] URLProtocolDidFinishLoading:self];
+ }
+ }];
+}
+
+- (void)stopLoading
+{}
+
+- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
+ willCacheResponse:(NSCachedURLResponse*)cachedResponse {
+ return nil;
+}
+
+@end
+
+
+@implementation CDVFile
+
+@synthesize rootDocsPath, appDocsPath, appLibraryPath, appTempPath, userHasAllowed, fileSystems=fileSystems_;
+
+- (void)registerFilesystem:(NSObject *)fs {
+ __weak CDVFile* weakSelf = self;
+ SEL sel = NSSelectorFromString(@"urlTransformer");
+ // for backwards compatibility - we check if this property is there
+ // we create a wrapper block because the urlTransformer property
+ // on the commandDelegate might be set dynamically at a future time
+ // (and not dependent on plugin loading order)
+ if ([self.commandDelegate respondsToSelector:sel]) {
+ fs.urlTransformer = ^NSURL*(NSURL* urlToTransform) {
+ // grab the block from the commandDelegate
+ NSURL* (^urlTransformer)(NSURL*) = ((id(*)(id, SEL))objc_msgSend)(weakSelf.commandDelegate, sel);
+ // if block is not null, we call it
+ if (urlTransformer) {
+ return urlTransformer(urlToTransform);
+ } else { // else we return the same url
+ return urlToTransform;
+ }
+ };
+ }
+ [fileSystems_ addObject:fs];
+}
+
+- (NSObject *)fileSystemByName:(NSString *)fsName
+{
+ if (self.fileSystems != nil) {
+ for (NSObject *fs in self.fileSystems) {
+ if ([fs.name isEqualToString:fsName]) {
+ return fs;
+ }
+ }
+ }
+ return nil;
+
+}
+
+- (NSObject *)filesystemForURL:(CDVFilesystemURL *)localURL {
+ if (localURL.fileSystemName == nil) return nil;
+ @try {
+ return [self fileSystemByName:localURL.fileSystemName];
+ }
+ @catch (NSException *e) {
+ return nil;
+ }
+}
+
+- (NSArray *)getExtraFileSystemsPreference:(UIViewController *)vc
+{
+ NSString *filesystemsStr = nil;
+ if([self.viewController isKindOfClass:[CDVViewController class]]) {
+ CDVViewController *vc = (CDVViewController *)self.viewController;
+ NSDictionary *settings = [vc settings];
+ filesystemsStr = [settings[@"iosextrafilesystems"] lowercaseString];
+ }
+ if (!filesystemsStr) {
+ filesystemsStr = @"library,library-nosync,documents,documents-nosync,cache,bundle,root";
+ }
+ return [filesystemsStr componentsSeparatedByString:@","];
+}
+
+- (void)makeNonSyncable:(NSString*)path {
+ [[NSFileManager defaultManager] createDirectoryAtPath:path
+ withIntermediateDirectories:YES
+ attributes:nil
+ error:nil];
+ NSURL* url = [NSURL fileURLWithPath:path];
+ [url setResourceValue: [NSNumber numberWithBool: YES]
+ forKey: NSURLIsExcludedFromBackupKey error:nil];
+
+}
+
+- (void)registerExtraFileSystems:(NSArray *)filesystems fromAvailableSet:(NSDictionary *)availableFileSystems
+{
+ NSMutableSet *installedFilesystems = [[NSMutableSet alloc] initWithCapacity:7];
+
+ /* Build non-syncable directories as necessary */
+ for (NSString *nonSyncFS in @[@"library-nosync", @"documents-nosync"]) {
+ if ([filesystems containsObject:nonSyncFS]) {
+ [self makeNonSyncable:availableFileSystems[nonSyncFS]];
+ }
+ }
+
+ /* Register filesystems in order */
+ for (NSString *fsName in filesystems) {
+ if (![installedFilesystems containsObject:fsName]) {
+ NSString *fsRoot = availableFileSystems[fsName];
+ if (fsRoot) {
+ [filePlugin registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:fsName root:fsRoot]];
+ [installedFilesystems addObject:fsName];
+ } else {
+ NSLog(@"Unrecognized extra filesystem identifier: %@", fsName);
+ }
+ }
+ }
+}
+
+- (NSDictionary *)getAvailableFileSystems
+{
+ NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
+ NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
+ return @{
+ @"library": libPath,
+ @"library-nosync": [libPath stringByAppendingPathComponent:@"NoCloud"],
+ @"documents": docPath,
+ @"documents-nosync": [docPath stringByAppendingPathComponent:@"NoCloud"],
+ @"cache": [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0],
+ @"bundle": [[NSBundle mainBundle] bundlePath],
+ @"root": @"/"
+ };
+}
+
+- (void)pluginInitialize
+{
+ filePlugin = self;
+ [NSURLProtocol registerClass:[CDVFilesystemURLProtocol class]];
+
+ fileSystems_ = [[NSMutableArray alloc] initWithCapacity:3];
+
+ // Get the Library directory path
+ NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
+ self.appLibraryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"files"];
+
+ // Get the Temporary directory path
+ self.appTempPath = [NSTemporaryDirectory()stringByStandardizingPath]; // remove trailing slash from NSTemporaryDirectory()
+
+ // Get the Documents directory path
+ paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
+ self.rootDocsPath = [paths objectAtIndex:0];
+ self.appDocsPath = [self.rootDocsPath stringByAppendingPathComponent:@"files"];
+
+
+ NSString *location = nil;
+ if([self.viewController isKindOfClass:[CDVViewController class]]) {
+ CDVViewController *vc = (CDVViewController *)self.viewController;
+ NSMutableDictionary *settings = vc.settings;
+ location = [[settings objectForKey:@"iospersistentfilelocation"] lowercaseString];
+ }
+ if (location == nil) {
+ // Compatibilty by default (if the config preference is not set, or
+ // if we're not embedded in a CDVViewController somehow.)
+ location = @"compatibility";
+ }
+
+ NSError *error;
+ if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appTempPath
+ withIntermediateDirectories:YES
+ attributes:nil
+ error:&error]) {
+ [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"temporary" root:self.appTempPath]];
+ } else {
+ NSLog(@"Unable to create temporary directory: %@", error);
+ }
+ if ([location isEqualToString:@"library"]) {
+ if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appLibraryPath
+ withIntermediateDirectories:YES
+ attributes:nil
+ error:&error]) {
+ [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.appLibraryPath]];
+ } else {
+ NSLog(@"Unable to create library directory: %@", error);
+ }
+ } else if ([location isEqualToString:@"compatibility"]) {
+ /*
+ * Fall-back to compatibility mode -- this is the logic implemented in
+ * earlier versions of this plugin, and should be maintained here so
+ * that apps which were originally deployed with older versions of the
+ * plugin can continue to provide access to files stored under those
+ * versions.
+ */
+ [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.rootDocsPath]];
+ } else {
+ NSAssert(false,
+ @"File plugin configuration error: Please set iosPersistentFileLocation in config.xml to one of \"library\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
+ }
+ [self registerFilesystem:[[CDVAssetLibraryFilesystem alloc] initWithName:@"assets-library"]];
+
+ [self registerExtraFileSystems:[self getExtraFileSystemsPreference:self.viewController]
+ fromAvailableSet:[self getAvailableFileSystems]];
+
+}
+
+- (CDVFilesystemURL *)fileSystemURLforArg:(NSString *)urlArg
+{
+ CDVFilesystemURL* ret = nil;
+ if ([urlArg hasPrefix:@"file://"]) {
+ /* This looks like a file url. Get the path, and see if any handlers recognize it. */
+ NSURL *fileURL = [NSURL URLWithString:urlArg];
+ NSURL *resolvedFileURL = [fileURL URLByResolvingSymlinksInPath];
+ NSString *path = [resolvedFileURL path];
+ ret = [self fileSystemURLforLocalPath:path];
+ } else {
+ ret = [CDVFilesystemURL fileSystemURLWithString:urlArg];
+ }
+ return ret;
+}
+
+- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath
+{
+ CDVFilesystemURL *localURL = nil;
+ NSUInteger shortestFullPath = 0;
+
+ // Try all installed filesystems, in order. Return the most match url.
+ for (id object in self.fileSystems) {
+ if ([object respondsToSelector:@selector(URLforFilesystemPath:)]) {
+ CDVFilesystemURL *url = [object URLforFilesystemPath:localPath];
+ if (url){
+ // A shorter fullPath would imply that the filesystem is a better match for the local path
+ if (!localURL || ([[url fullPath] length] < shortestFullPath)) {
+ localURL = url;
+ shortestFullPath = [[url fullPath] length];
+ }
+ }
+ }
+ }
+ return localURL;
+}
+
+- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath
+{
+ NSFileManager* fMgr = [[NSFileManager alloc] init];
+
+ NSError* __autoreleasing pError = nil;
+
+ NSDictionary* pDict = [fMgr attributesOfFileSystemForPath:appPath error:&pError];
+ NSNumber* pNumAvail = (NSNumber*)[pDict objectForKey:NSFileSystemFreeSize];
+
+ return pNumAvail;
+}
+
+/* Request the File System info
+ *
+ * IN:
+ * arguments[0] - type (number as string)
+ * TEMPORARY = 0, PERSISTENT = 1;
+ * arguments[1] - size
+ *
+ * OUT:
+ * Dictionary representing FileSystem object
+ * name - the human readable directory name
+ * root = DirectoryEntry object
+ * bool isDirectory
+ * bool isFile
+ * string name
+ * string fullPath
+ * fileSystem = FileSystem object - !! ignored because creates circular reference !!
+ */
+
+- (void)requestFileSystem:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ NSString* strType = [command argumentAtIndex:0];
+ unsigned long long size = [[command argumentAtIndex:1] longLongValue];
+
+ int type = [strType intValue];
+ CDVPluginResult* result = nil;
+
+ if (type > self.fileSystems.count) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR];
+ NSLog(@"No filesystem of type requested");
+ } else {
+ NSString* fullPath = @"/";
+ // check for avail space for size request
+ NSNumber* pNumAvail = [self checkFreeDiskSpace:self.rootDocsPath];
+ // NSLog(@"Free space: %@", [NSString stringWithFormat:@"%qu", [ pNumAvail unsignedLongLongValue ]]);
+ if (pNumAvail && ([pNumAvail unsignedLongLongValue] < size)) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:QUOTA_EXCEEDED_ERR];
+ } else {
+ NSObject *rootFs = [self.fileSystems objectAtIndex:type];
+ if (rootFs == nil) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR];
+ NSLog(@"No filesystem of type requested");
+ } else {
+ NSMutableDictionary* fileSystem = [NSMutableDictionary dictionaryWithCapacity:2];
+ [fileSystem setObject:rootFs.name forKey:@"name"];
+ NSDictionary* dirEntry = [self makeEntryForPath:fullPath fileSystemName:rootFs.name isDirectory:YES];
+ [fileSystem setObject:dirEntry forKey:@"root"];
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileSystem];
+ }
+ }
+ }
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+
+- (void)requestAllFileSystems:(CDVInvokedUrlCommand*)command
+{
+ NSMutableArray* ret = [[NSMutableArray alloc] init];
+ for (NSObject* root in fileSystems_) {
+ [ret addObject:[self makeEntryForPath:@"/" fileSystemName:root.name isDirectory:YES]];
+ }
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:ret];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+- (void)requestAllPaths:(CDVInvokedUrlCommand*)command
+{
+ NSString* libPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
+ NSString* libPathSync = [libPath stringByAppendingPathComponent:@"Cloud"];
+ NSString* libPathNoSync = [libPath stringByAppendingPathComponent:@"NoCloud"];
+ NSString* docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+ NSString* storagePath = [libPath stringByDeletingLastPathComponent];
+ NSString* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
+
+ // Create the directories if necessary.
+ [[NSFileManager defaultManager] createDirectoryAtPath:libPathSync withIntermediateDirectories:YES attributes:nil error:nil];
+ [[NSFileManager defaultManager] createDirectoryAtPath:libPathNoSync withIntermediateDirectories:YES attributes:nil error:nil];
+ // Mark NoSync as non-iCloud.
+ [[NSURL fileURLWithPath:libPathNoSync] setResourceValue: [NSNumber numberWithBool: YES]
+ forKey: NSURLIsExcludedFromBackupKey error:nil];
+
+ NSDictionary* ret = @{
+ @"applicationDirectory": [[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]] absoluteString],
+ @"applicationStorageDirectory": [[NSURL fileURLWithPath:storagePath] absoluteString],
+ @"dataDirectory": [[NSURL fileURLWithPath:libPathNoSync] absoluteString],
+ @"syncedDataDirectory": [[NSURL fileURLWithPath:libPathSync] absoluteString],
+ @"documentsDirectory": [[NSURL fileURLWithPath:docPath] absoluteString],
+ @"cacheDirectory": [[NSURL fileURLWithPath:cachePath] absoluteString],
+ @"tempDirectory": [[NSURL fileURLWithPath:NSTemporaryDirectory()] absoluteString]
+ };
+
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:ret];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/* Creates and returns a dictionary representing an Entry Object
+ *
+ * IN:
+ * NSString* fullPath of the entry
+ * int fsType - FileSystem type
+ * BOOL isDirectory - YES if this is a directory, NO if is a file
+ * OUT:
+ * NSDictionary* Entry object
+ * bool as NSNumber isDirectory
+ * bool as NSNumber isFile
+ * NSString* name - last part of path
+ * NSString* fullPath
+ * NSString* filesystemName - FileSystem name -- actual filesystem will be created on the JS side if necessary, to avoid
+ * creating circular reference (FileSystem contains DirectoryEntry which contains FileSystem.....!!)
+ */
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir
+{
+ NSObject *fs = [self fileSystemByName:fsName];
+ return [fs makeEntryForPath:fullPath isDirectory:isDir];
+}
+
+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)localURL
+{
+ NSObject *fs = [self filesystemForURL:localURL];
+ return [fs makeEntryForLocalURL:localURL];
+}
+
+- (NSDictionary *)makeEntryForURL:(NSURL *)URL
+{
+ CDVFilesystemURL* fsURL = [self fileSystemURLforArg:[URL absoluteString]];
+ return [self makeEntryForLocalURL:fsURL];
+}
+
+/*
+ * Given a URI determine the File System information associated with it and return an appropriate W3C entry object
+ * IN
+ * NSString* localURI: Should be an escaped local filesystem URI
+ * OUT
+ * Entry object
+ * bool isDirectory
+ * bool isFile
+ * string name
+ * string fullPath
+ * fileSystem = FileSystem object - !! ignored because creates circular reference FileSystem contains DirectoryEntry which contains FileSystem.....!!
+ */
+- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ NSString* localURIstr = [command argumentAtIndex:0];
+ CDVPluginResult* result;
+
+ localURIstr = [self encodePath:localURIstr]; //encode path before resolving
+ CDVFilesystemURL* inputURI = [self fileSystemURLforArg:localURIstr];
+
+ if (inputURI == nil || inputURI.fileSystemName == nil) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR];
+ } else {
+ NSObject *fs = [self filesystemForURL:inputURI];
+ if (fs == nil) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR];
+ } else {
+ result = [fs entryForLocalURI:inputURI];
+ }
+ }
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+//encode path with percent escapes
+-(NSString *)encodePath:(NSString *)path
+{
+ NSString *decodedPath = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //decode incase it's already encoded to avoid encoding twice
+ return [decodedPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
+}
+
+
+/* Part of DirectoryEntry interface, creates or returns the specified directory
+ * IN:
+ * NSString* localURI - local filesystem URI for this directory
+ * NSString* path - directory to be created/returned; may be full path or relative path
+ * NSDictionary* - Flags object
+ * boolean as NSNumber create -
+ * if create is true and directory does not exist, create dir and return directory entry
+ * if create is true and exclusive is true and directory does exist, return error
+ * if create is false and directory does not exist, return error
+ * if create is false and the path represents a file, return error
+ * boolean as NSNumber exclusive - used in conjunction with create
+ * if exclusive is true and create is true - specifies failure if directory already exists
+ *
+ *
+ */
+- (void)getDirectory:(CDVInvokedUrlCommand*)command
+{
+ NSMutableArray* arguments = [NSMutableArray arrayWithArray:command.arguments];
+ NSMutableDictionary* options = nil;
+
+ if ([arguments count] >= 3) {
+ options = [command argumentAtIndex:2 withDefault:nil];
+ }
+ // add getDir to options and call getFile()
+ if (options != nil) {
+ options = [NSMutableDictionary dictionaryWithDictionary:options];
+ } else {
+ options = [NSMutableDictionary dictionaryWithCapacity:1];
+ }
+ [options setObject:[NSNumber numberWithInt:1] forKey:@"getDir"];
+ if ([arguments count] >= 3) {
+ [arguments replaceObjectAtIndex:2 withObject:options];
+ } else {
+ [arguments addObject:options];
+ }
+ CDVInvokedUrlCommand* subCommand =
+ [[CDVInvokedUrlCommand alloc] initWithArguments:arguments
+ callbackId:command.callbackId
+ className:command.className
+ methodName:command.methodName];
+
+ [self getFile:subCommand];
+}
+
+/* Part of DirectoryEntry interface, creates or returns the specified file
+ * IN:
+ * NSString* baseURI - local filesytem URI for the base directory to search
+ * NSString* requestedPath - file to be created/returned; may be absolute path or relative path
+ * NSDictionary* options - Flags object
+ * boolean as NSNumber create -
+ * if create is true and file does not exist, create file and return File entry
+ * if create is true and exclusive is true and file does exist, return error
+ * if create is false and file does not exist, return error
+ * if create is false and the path represents a directory, return error
+ * boolean as NSNumber exclusive - used in conjunction with create
+ * if exclusive is true and create is true - specifies failure if file already exists
+ */
+- (void)getFile:(CDVInvokedUrlCommand*)command
+{
+ NSString* baseURIstr = [command argumentAtIndex:0];
+ CDVFilesystemURL* baseURI = [self fileSystemURLforArg:baseURIstr];
+ NSString* requestedPath = [command argumentAtIndex:1];
+ NSDictionary* options = [command argumentAtIndex:2 withDefault:nil];
+
+ NSObject *fs = [self filesystemForURL:baseURI];
+ CDVPluginResult* result = [fs getFileForURL:baseURI requestedPath:requestedPath options:options];
+
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/*
+ * Look up the parent Entry containing this Entry.
+ * If this Entry is the root of its filesystem, its parent is itself.
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* localURI
+ * NSMutableDictionary* options
+ * empty
+ */
+- (void)getParent:(CDVInvokedUrlCommand*)command
+{
+ // arguments are URL encoded
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+ CDVPluginResult* result = [fs getParentForURL:localURI];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/*
+ * set MetaData of entry
+ * Currently we only support "com.apple.MobileBackup" (boolean)
+ */
+- (void)setMetadata:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSDictionary* options = [command argumentAtIndex:1 withDefault:nil];
+ NSObject *fs = [self filesystemForURL:localURI];
+ CDVPluginResult* result = [fs setMetadataForURL:localURI withObject:options];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/* removes the directory or file entry
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* localURI
+ *
+ * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir
+ * returns INVALID_MODIFICATION_ERR if is non-empty dir or asset library file
+ * returns NOT_FOUND_ERR if file or dir is not found
+*/
+- (void)remove:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ CDVPluginResult* result = nil;
+
+ if ([localURI.fullPath isEqualToString:@""]) {
+ // error if try to remove top level (documents or tmp) dir
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
+ } else {
+ NSObject *fs = [self filesystemForURL:localURI];
+ result = [fs removeFileAtURL:localURI];
+ }
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/* recursively removes the directory
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* localURI
+ *
+ * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir
+ * returns NOT_FOUND_ERR if file or dir is not found
+ */
+- (void)removeRecursively:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ CDVPluginResult* result = nil;
+
+ if ([localURI.fullPath isEqualToString:@""]) {
+ // error if try to remove top level (documents or tmp) dir
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
+ } else {
+ NSObject *fs = [self filesystemForURL:localURI];
+ result = [fs recursiveRemoveFileAtURL:localURI];
+ }
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+- (void)copyTo:(CDVInvokedUrlCommand*)command
+{
+ [self doCopyMove:command isCopy:YES];
+}
+
+- (void)moveTo:(CDVInvokedUrlCommand*)command
+{
+ [self doCopyMove:command isCopy:NO];
+}
+
+/* Copy/move a file or directory to a new location
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* URL of entry to copy
+ * 1 - NSString* URL of the directory into which to copy/move the entry
+ * 2 - Optionally, the new name of the entry, defaults to the current name
+ * BOOL - bCopy YES if copy, NO if move
+ */
+- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy
+{
+ NSArray* arguments = command.arguments;
+
+ // arguments
+ NSString* srcURLstr = [command argumentAtIndex:0];
+ NSString* destURLstr = [command argumentAtIndex:1];
+
+ CDVPluginResult *result;
+
+ if (!srcURLstr || !destURLstr) {
+ // either no source or no destination provided
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return;
+ }
+
+ CDVFilesystemURL* srcURL = [self fileSystemURLforArg:srcURLstr];
+ CDVFilesystemURL* destURL = [self fileSystemURLforArg:destURLstr];
+
+ NSObject *srcFs = [self filesystemForURL:srcURL];
+ NSObject *destFs = [self filesystemForURL:destURL];
+
+ // optional argument; use last component from srcFullPath if new name not provided
+ NSString* newName = ([arguments count] > 2) ? [command argumentAtIndex:2] : [srcURL.url lastPathComponent];
+ if ([newName rangeOfString:@":"].location != NSNotFound) {
+ // invalid chars in new name
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return;
+ }
+
+ [destFs copyFileToURL:destURL withName:newName fromFileSystem:srcFs atURL:srcURL copy:bCopy callback:^(CDVPluginResult* result) {
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ }];
+
+}
+
+- (void)getFileMetadata:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSObject *fs = [self filesystemForURL:localURI];
+
+ [fs getFileMetadataForURL:localURI callback:^(CDVPluginResult* result) {
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ }];
+}
+
+- (void)readEntries:(CDVInvokedUrlCommand*)command
+{
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSObject *fs = [self filesystemForURL:localURI];
+ CDVPluginResult *result = [fs readEntriesAtURL:localURI];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/* read and return file data
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* fullPath
+ * 1 - NSString* encoding
+ * 2 - NSString* start
+ * 3 - NSString* end
+ */
+- (void)readAsText:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSString* encoding = [command argumentAtIndex:1];
+ NSInteger start = [[command argumentAtIndex:2] integerValue];
+ NSInteger end = [[command argumentAtIndex:3] integerValue];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+
+ if (fs == nil) {
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return;
+ }
+
+ // TODO: implement
+ if ([@"UTF-8" caseInsensitiveCompare : encoding] != NSOrderedSame) {
+ NSLog(@"Only UTF-8 encodings are currently supported by readAsText");
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR];
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ return;
+ }
+
+ [self.commandDelegate runInBackground:^ {
+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
+ CDVPluginResult* result = nil;
+ if (data != nil) {
+ NSString* str = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSUTF8StringEncoding freeWhenDone:NO];
+ // Check that UTF8 conversion did not fail.
+ if (str != nil) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:str];
+ result.associatedObject = data;
+ } else {
+ errorCode = ENCODING_ERR;
+ }
+ }
+ if (result == nil) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ }];
+ }];
+}
+
+/* Read content of text file and return as base64 encoded data url.
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* fullPath
+ * 1 - NSString* start
+ * 2 - NSString* end
+ *
+ * Determines the mime type from the file extension, returns ENCODING_ERR if mimetype can not be determined.
+ */
+
+- (void)readAsDataURL:(CDVInvokedUrlCommand*)command
+{
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSInteger start = [[command argumentAtIndex:1] integerValue];
+ NSInteger end = [[command argumentAtIndex:2] integerValue];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+
+ [self.commandDelegate runInBackground:^ {
+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
+ CDVPluginResult* result = nil;
+ if (data != nil) {
+ NSString* b64Str = toBase64(data);
+ NSString* output = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, b64Str];
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:output];
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ }];
+ }];
+}
+
+/* Read content of text file and return as an arraybuffer
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* fullPath
+ * 1 - NSString* start
+ * 2 - NSString* end
+ */
+
+- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command
+{
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSInteger start = [[command argumentAtIndex:1] integerValue];
+ NSInteger end = [[command argumentAtIndex:2] integerValue];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+
+ [self.commandDelegate runInBackground:^ {
+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
+ CDVPluginResult* result = nil;
+ if (data != nil) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArrayBuffer:data];
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ }];
+ }];
+}
+
+- (void)readAsBinaryString:(CDVInvokedUrlCommand*)command
+{
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ NSInteger start = [[command argumentAtIndex:1] integerValue];
+ NSInteger end = [[command argumentAtIndex:2] integerValue];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+
+ [self.commandDelegate runInBackground:^ {
+ [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
+ CDVPluginResult* result = nil;
+ if (data != nil) {
+ NSString* payload = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSASCIIStringEncoding freeWhenDone:NO];
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload];
+ result.associatedObject = data;
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+ }];
+ }];
+}
+
+
+- (void)truncate:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ unsigned long long pos = (unsigned long long)[[command argumentAtIndex:1] longLongValue];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+ CDVPluginResult *result = [fs truncateFileAtURL:localURI atPosition:pos];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+/* write
+ * IN:
+ * NSArray* arguments
+ * 0 - NSString* localURI of file to write to
+ * 1 - NSString* or NSData* data to write
+ * 2 - NSNumber* position to begin writing
+ */
+- (void)write:(CDVInvokedUrlCommand*)command
+{
+ [self.commandDelegate runInBackground:^ {
+ NSString* callbackId = command.callbackId;
+
+ // arguments
+ CDVFilesystemURL* localURI = [self fileSystemURLforArg:command.arguments[0]];
+ id argData = [command argumentAtIndex:1];
+ unsigned long long pos = (unsigned long long)[[command argumentAtIndex:2] longLongValue];
+
+ NSObject *fs = [self filesystemForURL:localURI];
+
+
+ [fs truncateFileAtURL:localURI atPosition:pos];
+ CDVPluginResult *result;
+ if ([argData isKindOfClass:[NSString class]]) {
+ NSData *encData = [argData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
+ result = [fs writeToFileAtURL:localURI withData:encData append:YES];
+ } else if ([argData isKindOfClass:[NSData class]]) {
+ result = [fs writeToFileAtURL:localURI withData:argData append:YES];
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid parameter type"];
+ }
+ [self.commandDelegate sendPluginResult:result callbackId:callbackId];
+ }];
+}
+
+#pragma mark Methods for converting between URLs and paths
+
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURL
+{
+ for (NSObject *fs in self.fileSystems) {
+ if ([fs.name isEqualToString:localURL.fileSystemName]) {
+ if ([fs respondsToSelector:@selector(filesystemPathForURL:)]) {
+ return [fs filesystemPathForURL:localURL];
+ }
+ }
+ }
+ return nil;
+}
+
+#pragma mark Undocumented Filesystem API
+
+- (void)testFileExists:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ NSString* argPath = [command argumentAtIndex:0];
+
+ // Get the file manager
+ NSFileManager* fMgr = [NSFileManager defaultManager];
+ NSString* appFile = argPath; // [ self getFullPath: argPath];
+
+ BOOL bExists = [fMgr fileExistsAtPath:appFile];
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(bExists ? 1 : 0)];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command
+{
+ // arguments
+ NSString* argPath = [command argumentAtIndex:0];
+
+ // Get the file manager
+ NSFileManager* fMgr = [[NSFileManager alloc] init];
+ NSString* appFile = argPath; // [self getFullPath: argPath];
+ BOOL bIsDir = NO;
+ BOOL bExists = [fMgr fileExistsAtPath:appFile isDirectory:&bIsDir];
+
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:((bExists && bIsDir) ? 1 : 0)];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+// Returns number of bytes available via callback
+- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command
+{
+ // no arguments
+
+ NSNumber* pNumAvail = [self checkFreeDiskSpace:self.appDocsPath];
+
+ NSString* strFreeSpace = [NSString stringWithFormat:@"%qu", [pNumAvail unsignedLongLongValue]];
+ // NSLog(@"Free space is %@", strFreeSpace );
+
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:strFreeSpace];
+
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+#pragma mark Compatibility with older File API
+
+- (NSString*)getMimeTypeFromPath:(NSString*)fullPath
+{
+ return [CDVLocalFilesystem getMimeTypeFromPath:fullPath];
+}
+
+- (NSDictionary *)getDirectoryEntry:(NSString *)localPath isDirectory:(BOOL)bDirRequest
+{
+ CDVFilesystemURL *localURL = [self fileSystemURLforLocalPath:localPath];
+ return [self makeEntryForPath:localURL.fullPath fileSystemName:localURL.fileSystemName isDirectory:bDirRequest];
+}
+
+#pragma mark Internal methods for testing
+// Internal methods for testing: Get the on-disk location of a local filesystem url.
+// [Currently used for testing file-transfer]
+
+- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command
+{
+ CDVFilesystemURL* localURL = [self fileSystemURLforArg:command.arguments[0]];
+
+ NSString* fsPath = [self filesystemPathForURL:localURL];
+ CDVPluginResult* result;
+ if (fsPath) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fsPath];
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot resolve URL to a file"];
+ }
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
+}
+
+@end
diff --git a/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h
new file mode 100644
index 0000000..a0186c8
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.h
@@ -0,0 +1,32 @@
+/*
+ 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.
+ */
+
+#import "CDVFile.h"
+
+@interface CDVLocalFilesystem : NSObject {
+ NSString *_name;
+ NSString *_fsRoot;
+}
+
+- (id) initWithName:(NSString *)name root:(NSString *)fsRoot;
++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath;
+
+@property (nonatomic,strong) NSString *fsRoot;
+
+@end
diff --git a/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m
new file mode 100644
index 0000000..72bc421
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ios/CDVLocalFilesystem.m
@@ -0,0 +1,734 @@
+/*
+ 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.
+ */
+
+#import "CDVFile.h"
+#import "CDVLocalFilesystem.h"
+#import
+#import
+#import
+
+@implementation CDVLocalFilesystem
+@synthesize name=_name, fsRoot=_fsRoot, urlTransformer;
+
+- (id) initWithName:(NSString *)name root:(NSString *)fsRoot
+{
+ if (self) {
+ _name = name;
+ _fsRoot = fsRoot;
+ }
+ return self;
+}
+
+/*
+ * IN
+ * NSString localURI
+ * OUT
+ * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the
+ * URI represents a non-existent path, or is unrecognized or otherwise malformed.
+ */
+- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
+{
+ CDVPluginResult* result = nil;
+ NSDictionary* entry = [self makeEntryForLocalURL:url];
+ if (entry) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
+ } else {
+ // return NOT_FOUND_ERR
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
+ }
+ return result;
+}
+- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
+ NSString *path = [self filesystemPathForURL:url];
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+ BOOL isDir = NO;
+ // see if exists and is file or dir
+ BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir];
+ if (bExists) {
+ return [self makeEntryForPath:url.fullPath isDirectory:isDir];
+ } else {
+ return nil;
+ }
+}
+- (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir
+{
+ NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
+ NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent];
+ if (isDir && ![fullPath hasSuffix:@"/"]) {
+ fullPath = [fullPath stringByAppendingString:@"/"];
+ }
+ [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
+ [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
+ [dirEntry setObject:fullPath forKey:@"fullPath"];
+ [dirEntry setObject:lastPart forKey:@"name"];
+ [dirEntry setObject:self.name forKey: @"filesystemName"];
+
+ NSURL* nativeURL = [NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]];
+ if (self.urlTransformer) {
+ nativeURL = self.urlTransformer(nativeURL);
+ }
+
+ dirEntry[@"nativeURL"] = [nativeURL absoluteString];
+
+ return dirEntry;
+}
+
+- (NSString *)stripQueryParametersFromPath:(NSString *)fullPath
+{
+ NSRange questionMark = [fullPath rangeOfString:@"?"];
+ if (questionMark.location != NSNotFound) {
+ return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)];
+ }
+ return fullPath;
+}
+
+- (NSString *)filesystemPathForFullPath:(NSString *)fullPath
+{
+ NSString *path = nil;
+ NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath];
+ path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath];
+ if ([path length] > 1 && [path hasSuffix:@"/"]) {
+ path = [path substringToIndex:([path length]-1)];
+ }
+ return path;
+}
+/*
+ * IN
+ * NSString localURI
+ * OUT
+ * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
+ * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
+ * or if the URL is malformed.
+ * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
+ */
+- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
+{
+ return [self filesystemPathForFullPath:url.fullPath];
+}
+
+- (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath
+{
+ if (fullPath) {
+ NSString* escapedPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
+ if ([fullPath hasPrefix:@"/"]) {
+ return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];
+ }
+ return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];
+ }
+ return nil;
+}
+
+- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path
+{
+ return [self URLforFullPath:[self fullPathForFileSystemPath:path]];
+
+}
+
+- (NSString *)normalizePath:(NSString *)rawPath
+{
+ // If this is an absolute path, the first path component will be '/'. Skip it if that's the case
+ BOOL isAbsolutePath = [rawPath hasPrefix:@"/"];
+ if (isAbsolutePath) {
+ rawPath = [rawPath substringFromIndex:1];
+ }
+ NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]];
+ for (int index = 0; index < [components count]; ++index) {
+ if ([[components objectAtIndex:index] isEqualToString:@".."]) {
+ [components removeObjectAtIndex:index];
+ if (index > 0) {
+ [components removeObjectAtIndex:index-1];
+ --index;
+ }
+ }
+ }
+
+ if (isAbsolutePath) {
+ return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]];
+ } else {
+ return [components componentsJoinedByString:@"/"];
+ }
+
+
+}
+
+- (BOOL)valueForKeyIsNumber:(NSDictionary*)dict key:(NSString*)key
+{
+ BOOL bNumber = NO;
+ NSObject* value = dict[key];
+ if (value) {
+ bNumber = [value isKindOfClass:[NSNumber class]];
+ }
+ return bNumber;
+}
+
+- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
+{
+ CDVPluginResult* result = nil;
+ BOOL bDirRequest = NO;
+ BOOL create = NO;
+ BOOL exclusive = NO;
+ int errorCode = 0; // !!! risky - no error code currently defined for 0
+
+ if ([self valueForKeyIsNumber:options key:@"create"]) {
+ create = [(NSNumber*)[options valueForKey:@"create"] boolValue];
+ }
+ if ([self valueForKeyIsNumber:options key:@"exclusive"]) {
+ exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue];
+ }
+ if ([self valueForKeyIsNumber:options key:@"getDir"]) {
+ // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method
+ bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue];
+ }
+ // see if the requested path has invalid characters - should we be checking for more than just ":"?
+ if ([requestedPath rangeOfString:@":"].location != NSNotFound) {
+ errorCode = ENCODING_ERR;
+ } else {
+ // Build new fullPath for the requested resource.
+ // We concatenate the two paths together, and then scan the resulting string to remove
+ // parent ("..") references. Any parent references at the beginning of the string are
+ // silently removed.
+ NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:requestedPath];
+ combinedPath = [self normalizePath:combinedPath];
+ CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath];
+
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+ BOOL bIsDir;
+ BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir];
+ if (bExists && (create == NO) && (bIsDir == !bDirRequest)) {
+ // path exists and is not of requested type - return TYPE_MISMATCH_ERR
+ errorCode = TYPE_MISMATCH_ERR;
+ } else if (!bExists && (create == NO)) {
+ // path does not exist and create is false - return NOT_FOUND_ERR
+ errorCode = NOT_FOUND_ERR;
+ } else if (bExists && (create == YES) && (exclusive == YES)) {
+ // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR
+ errorCode = PATH_EXISTS_ERR;
+ } else {
+ // if bExists and create == YES - just return data
+ // if bExists and create == NO - just return data
+ // if !bExists and create == YES - create and return data
+ BOOL bSuccess = YES;
+ NSError __autoreleasing* pError = nil;
+ if (!bExists && (create == YES)) {
+ if (bDirRequest) {
+ // create the dir
+ bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError];
+ } else {
+ // create the empty file
+ bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil];
+ }
+ }
+ if (!bSuccess) {
+ errorCode = ABORT_ERR;
+ if (pError) {
+ NSLog(@"error creating directory: %@", [pError localizedDescription]);
+ }
+ } else {
+ // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]);
+ // file existed or was created
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath isDirectory:bDirRequest]];
+ }
+ } // are all possible conditions met?
+ }
+
+ if (errorCode > 0) {
+ // create error callback
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+ return result;
+
+}
+
+- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
+{
+ CDVPluginResult* result = nil;
+ CDVFilesystemURL *newURI = nil;
+ if ([localURI.fullPath isEqualToString:@""]) {
+ // return self
+ newURI = localURI;
+ } else {
+ newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */
+ }
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+ BOOL bIsDir;
+ BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir];
+ if (bExists) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath isDirectory:bIsDir]];
+ } else {
+ // invalid path or file does not exist
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
+ }
+ return result;
+}
+
+- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
+{
+ BOOL ok = NO;
+
+ NSString* filePath = [self filesystemPathForURL:localURI];
+ // we only care about this iCloud key for now.
+ // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute)
+ NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup";
+ id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey];
+
+ if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) {
+ if (IsAtLeastiOSVersion(@"5.1")) {
+ NSURL* url = [NSURL fileURLWithPath:filePath];
+ NSError* __autoreleasing error = nil;
+
+ ok = [url setResourceValue:[NSNumber numberWithBool:[iCloudBackupExtendedAttributeValue boolValue]] forKey:NSURLIsExcludedFromBackupKey error:&error];
+ } else { // below 5.1 (deprecated - only really supported in 5.01)
+ u_int8_t value = [iCloudBackupExtendedAttributeValue intValue];
+ if (value == 0) { // remove the attribute (allow backup, the default)
+ ok = (removexattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], 0) == 0);
+ } else { // set the attribute (skip backup)
+ ok = (setxattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], &value, sizeof(value), 0, 0) == 0);
+ }
+ }
+ }
+
+ if (ok) {
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
+ } else {
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
+ }
+}
+
+/* remove the file or directory (recursively)
+ * IN:
+ * NSString* fullPath - the full path to the file or directory to be removed
+ * NSString* callbackId
+ * called from remove and removeRecursively - check all pubic api specific error conditions (dir not empty, etc) before calling
+ */
+
+- (CDVPluginResult*)doRemove:(NSString*)fullPath
+{
+ CDVPluginResult* result = nil;
+ BOOL bSuccess = NO;
+ NSError* __autoreleasing pError = nil;
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+
+ @try {
+ bSuccess = [fileMgr removeItemAtPath:fullPath error:&pError];
+ if (bSuccess) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
+ } else {
+ // see if we can give a useful error
+ CDVFileError errorCode = ABORT_ERR;
+ NSLog(@"error removing filesystem entry at %@: %@", fullPath, [pError localizedDescription]);
+ if ([pError code] == NSFileNoSuchFileError) {
+ errorCode = NOT_FOUND_ERR;
+ } else if ([pError code] == NSFileWriteNoPermissionError) {
+ errorCode = NO_MODIFICATION_ALLOWED_ERR;
+ }
+
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+ } @catch(NSException* e) { // NSInvalidArgumentException if path is . or ..
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:SYNTAX_ERR];
+ }
+
+ return result;
+}
+
+- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
+{
+ NSString *fileSystemPath = [self filesystemPathForURL:localURI];
+
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+ BOOL bIsDir = NO;
+ BOOL bExists = [fileMgr fileExistsAtPath:fileSystemPath isDirectory:&bIsDir];
+ if (!bExists) {
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
+ }
+ if (bIsDir && ([[fileMgr contentsOfDirectoryAtPath:fileSystemPath error:nil] count] != 0)) {
+ // dir is not empty
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
+ }
+ return [self doRemove:fileSystemPath];
+}
+
+- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
+{
+ NSString *fileSystemPath = [self filesystemPathForURL:localURI];
+ return [self doRemove:fileSystemPath];
+}
+
+/*
+ * IN
+ * NSString localURI
+ * OUT
+ * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
+ * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
+ * or if the URL is malformed.
+ * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
+ */
+- (NSString *)fullPathForFileSystemPath:(NSString *)fsPath
+{
+ if ([fsPath hasPrefix:self.fsRoot]) {
+ return [fsPath substringFromIndex:[self.fsRoot length]];
+ }
+ return nil;
+}
+
+
+- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
+{
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+ NSError* __autoreleasing error = nil;
+ NSString *fileSystemPath = [self filesystemPathForURL:localURI];
+
+ NSArray* contents = [fileMgr contentsOfDirectoryAtPath:fileSystemPath error:&error];
+
+ if (contents) {
+ NSMutableArray* entries = [NSMutableArray arrayWithCapacity:1];
+ if ([contents count] > 0) {
+ // create an Entry (as JSON) for each file/dir
+ for (NSString* name in contents) {
+ // see if is dir or file
+ NSString* entryPath = [fileSystemPath stringByAppendingPathComponent:name];
+ BOOL bIsDir = NO;
+ [fileMgr fileExistsAtPath:entryPath isDirectory:&bIsDir];
+ NSDictionary* entryDict = [self makeEntryForPath:[self fullPathForFileSystemPath:entryPath] isDirectory:bIsDir];
+ [entries addObject:entryDict];
+ }
+ }
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:entries];
+ } else {
+ // assume not found but could check error for more specific error conditions
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
+ }
+}
+
+- (unsigned long long)truncateFile:(NSString*)filePath atPosition:(unsigned long long)pos
+{
+ unsigned long long newPos = 0UL;
+
+ NSFileHandle* file = [NSFileHandle fileHandleForWritingAtPath:filePath];
+
+ if (file) {
+ [file truncateFileAtOffset:(unsigned long long)pos];
+ newPos = [file offsetInFile];
+ [file synchronizeFile];
+ [file closeFile];
+ }
+ return newPos;
+}
+
+- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
+{
+ unsigned long long newPos = [self truncateFile:[self filesystemPathForURL:localURI] atPosition:pos];
+ return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)newPos];
+}
+
+- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
+{
+ NSString *filePath = [self filesystemPathForURL:localURL];
+
+ CDVPluginResult* result = nil;
+ CDVFileError errCode = INVALID_MODIFICATION_ERR;
+ int bytesWritten = 0;
+
+ if (filePath) {
+ NSOutputStream* fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:shouldAppend];
+ if (fileStream) {
+ NSUInteger len = [encData length];
+ if (len == 0) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:(double)len];
+ } else {
+ [fileStream open];
+
+ bytesWritten = (int)[fileStream write:[encData bytes] maxLength:len];
+
+ [fileStream close];
+ if (bytesWritten > 0) {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:bytesWritten];
+ // } else {
+ // can probably get more detailed error info via [fileStream streamError]
+ // errCode already set to INVALID_MODIFICATION_ERR;
+ // bytesWritten = 0; // may be set to -1 on error
+ }
+ }
+ } // else fileStream not created return INVALID_MODIFICATION_ERR
+ } else {
+ // invalid filePath
+ errCode = NOT_FOUND_ERR;
+ }
+ if (!result) {
+ // was an error
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errCode];
+ }
+ return result;
+}
+
+/**
+ * Helper function to check to see if the user attempted to copy an entry into its parent without changing its name,
+ * or attempted to copy a directory into a directory that it contains directly or indirectly.
+ *
+ * IN:
+ * NSString* srcDir
+ * NSString* destinationDir
+ * OUT:
+ * YES copy/ move is allows
+ * NO move is onto itself
+ */
+- (BOOL)canCopyMoveSrc:(NSString*)src ToDestination:(NSString*)dest
+{
+ // This weird test is to determine if we are copying or moving a directory into itself.
+ // Copy /Documents/myDir to /Documents/myDir-backup is okay but
+ // Copy /Documents/myDir to /Documents/myDir/backup not okay
+ BOOL copyOK = YES;
+ NSRange range = [dest rangeOfString:src];
+
+ if (range.location != NSNotFound) {
+ NSRange testRange = {range.length - 1, ([dest length] - range.length)};
+ NSRange resultRange = [dest rangeOfString:@"/" options:0 range:testRange];
+ if (resultRange.location != NSNotFound) {
+ copyOK = NO;
+ }
+ }
+ return copyOK;
+}
+
+- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
+{
+ NSFileManager *fileMgr = [[NSFileManager alloc] init];
+ NSString *destRootPath = [self filesystemPathForURL:destURL];
+ BOOL bDestIsDir = NO;
+ BOOL bDestExists = [fileMgr fileExistsAtPath:destRootPath isDirectory:&bDestIsDir];
+
+ NSString *newFileSystemPath = [destRootPath stringByAppendingPathComponent:newName];
+ NSString *newFullPath = [self fullPathForFileSystemPath:newFileSystemPath];
+
+ BOOL bNewIsDir = NO;
+ BOOL bNewExists = [fileMgr fileExistsAtPath:newFileSystemPath isDirectory:&bNewIsDir];
+
+ CDVPluginResult *result = nil;
+ int errCode = 0;
+
+ if (!bDestExists) {
+ // the destination root does not exist
+ errCode = NOT_FOUND_ERR;
+ }
+
+ else if ([srcFs isKindOfClass:[CDVLocalFilesystem class]]) {
+ /* Same FS, we can shortcut with NSFileManager operations */
+ NSString *srcFullPath = [srcFs filesystemPathForURL:srcURL];
+
+ BOOL bSrcIsDir = NO;
+ BOOL bSrcExists = [fileMgr fileExistsAtPath:srcFullPath isDirectory:&bSrcIsDir];
+
+ if (!bSrcExists) {
+ // the source does not exist
+ errCode = NOT_FOUND_ERR;
+ } else if ([newFileSystemPath isEqualToString:srcFullPath]) {
+ // source and destination can not be the same
+ errCode = INVALID_MODIFICATION_ERR;
+ } else if (bSrcIsDir && (bNewExists && !bNewIsDir)) {
+ // can't copy/move dir to file
+ errCode = INVALID_MODIFICATION_ERR;
+ } else { // no errors yet
+ NSError* __autoreleasing error = nil;
+ BOOL bSuccess = NO;
+ if (bCopy) {
+ if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {
+ // can't copy dir into self
+ errCode = INVALID_MODIFICATION_ERR;
+ } else if (bNewExists) {
+ // the full destination should NOT already exist if a copy
+ errCode = PATH_EXISTS_ERR;
+ } else {
+ bSuccess = [fileMgr copyItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];
+ }
+ } else { // move
+ // iOS requires that destination must not exist before calling moveTo
+ // is W3C INVALID_MODIFICATION_ERR error if destination dir exists and has contents
+ //
+ if (!bSrcIsDir && (bNewExists && bNewIsDir)) {
+ // can't move a file to directory
+ errCode = INVALID_MODIFICATION_ERR;
+ } else if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {
+ // can't move a dir into itself
+ errCode = INVALID_MODIFICATION_ERR;
+ } else if (bNewExists) {
+ if (bNewIsDir && ([[fileMgr contentsOfDirectoryAtPath:newFileSystemPath error:NULL] count] != 0)) {
+ // can't move dir to a dir that is not empty
+ errCode = INVALID_MODIFICATION_ERR;
+ newFileSystemPath = nil; // so we won't try to move
+ } else {
+ // remove destination so can perform the moveItemAtPath
+ bSuccess = [fileMgr removeItemAtPath:newFileSystemPath error:NULL];
+ if (!bSuccess) {
+ errCode = INVALID_MODIFICATION_ERR; // is this the correct error?
+ newFileSystemPath = nil;
+ }
+ }
+ } else if (bNewIsDir && [newFileSystemPath hasPrefix:srcFullPath]) {
+ // can't move a directory inside itself or to any child at any depth;
+ errCode = INVALID_MODIFICATION_ERR;
+ newFileSystemPath = nil;
+ }
+
+ if (newFileSystemPath != nil) {
+ bSuccess = [fileMgr moveItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];
+ }
+ }
+ if (bSuccess) {
+ // should verify it is there and of the correct type???
+ NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:bSrcIsDir];
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];
+ } else {
+ if (error) {
+ if (([error code] == NSFileReadUnknownError) || ([error code] == NSFileReadTooLargeError)) {
+ errCode = NOT_READABLE_ERR;
+ } else if ([error code] == NSFileWriteOutOfSpaceError) {
+ errCode = QUOTA_EXCEEDED_ERR;
+ } else if ([error code] == NSFileWriteNoPermissionError) {
+ errCode = NO_MODIFICATION_ALLOWED_ERR;
+ }
+ }
+ }
+ }
+ } else {
+ // Need to copy the hard way
+ [srcFs readFileAtURL:srcURL start:0 end:-1 callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
+ CDVPluginResult* result = nil;
+ if (data != nil) {
+ BOOL bSuccess = [data writeToFile:newFileSystemPath atomically:YES];
+ if (bSuccess) {
+ // should verify it is there and of the correct type???
+ NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:NO];
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ABORT_ERR];
+ }
+ } else {
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
+ }
+ callback(result);
+ }];
+ return; // Async IO; return without callback.
+ }
+ if (result == nil) {
+ if (!errCode) {
+ errCode = INVALID_MODIFICATION_ERR; // Catch-all default
+ }
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errCode];
+ }
+ callback(result);
+}
+
+/* helper function to get the mimeType from the file extension
+ * IN:
+ * NSString* fullPath - filename (may include path)
+ * OUT:
+ * NSString* the mime type as type/subtype. nil if not able to determine
+ */
++ (NSString*)getMimeTypeFromPath:(NSString*)fullPath
+{
+ NSString* mimeType = nil;
+
+ if (fullPath) {
+ CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
+ if (typeId) {
+ mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
+ if (!mimeType) {
+ // special case for m4a
+ if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
+ mimeType = @"audio/mp4";
+ } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
+ mimeType = @"audio/wav";
+ } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
+ mimeType = @"text/css";
+ }
+ }
+ CFRelease(typeId);
+ }
+ }
+ return mimeType;
+}
+
+- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
+{
+ NSString *path = [self filesystemPathForURL:localURL];
+
+ NSString* mimeType = [CDVLocalFilesystem getMimeTypeFromPath:path];
+ if (mimeType == nil) {
+ mimeType = @"*/*";
+ }
+ NSFileHandle* file = [NSFileHandle fileHandleForReadingAtPath:path];
+ if (start > 0) {
+ [file seekToFileOffset:start];
+ }
+
+ NSData* readData;
+ if (end < 0) {
+ readData = [file readDataToEndOfFile];
+ } else {
+ readData = [file readDataOfLength:(end - start)];
+ }
+ [file closeFile];
+
+ callback(readData, mimeType, readData != nil ? NO_ERROR : NOT_FOUND_ERR);
+}
+
+- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
+{
+ NSString *path = [self filesystemPathForURL:localURL];
+ CDVPluginResult *result;
+ NSFileManager* fileMgr = [[NSFileManager alloc] init];
+
+ NSError* __autoreleasing error = nil;
+ NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:path error:&error];
+
+ if (fileAttrs) {
+
+ // create dictionary of file info
+ NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
+
+ [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
+ [fileInfo setObject:@"" forKey:@"type"]; // can't easily get the mimetype unless create URL, send request and read response so skipping
+ [fileInfo setObject:[path lastPathComponent] forKey:@"name"];
+
+ // Ensure that directories (and other non-regular files) report size of 0
+ unsigned long long size = ([fileAttrs fileType] == NSFileTypeRegular ? [fileAttrs fileSize] : 0);
+ [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:size] forKey:@"size"];
+
+ NSDate* modDate = [fileAttrs fileModificationDate];
+ if (modDate) {
+ [fileInfo setObject:[NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000] forKey:@"lastModifiedDate"];
+ }
+
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo];
+
+ } else {
+ // didn't get fileAttribs
+ CDVFileError errorCode = ABORT_ERR;
+ NSLog(@"error getting metadata: %@", [error localizedDescription]);
+ if ([error code] == NSFileNoSuchFileError || [error code] == NSFileReadNoSuchFileError) {
+ errorCode = NOT_FOUND_ERR;
+ }
+ // log [NSNumber numberWithDouble: theMessage] objCtype to see what it returns
+ result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errorCode];
+ }
+
+ callback(result);
+}
+
+@end
diff --git a/plugins/cordova-plugin-file/src/ubuntu/file.cpp b/plugins/cordova-plugin-file/src/ubuntu/file.cpp
new file mode 100644
index 0000000..395ab2d
--- /dev/null
+++ b/plugins/cordova-plugin-file/src/ubuntu/file.cpp
@@ -0,0 +1,912 @@
+/*
+ * Licensed 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.
+ */
+
+#include "file.h"
+
+#include