Cordova plugin file und file-transfer geadded
This commit is contained in:
311
plugins/cordova-plugin-file-transfer/doc/de/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/de/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
Plugin-Dokumentation: <doc/index.md>
|
||||
|
||||
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 <code>FileTransfer`-Upload()-Methode</code> ü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/<application UUID>/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.
|
||||
302
plugins/cordova-plugin-file-transfer/doc/de/index.md
Normal file
302
plugins/cordova-plugin-file-transfer/doc/de/index.md
Normal file
@@ -0,0 +1,302 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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 <code>FileTransfer`-Upload()-Methode</code> ü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/<application UUID>/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.
|
||||
311
plugins/cordova-plugin-file-transfer/doc/es/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/es/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
Documentación del plugin: <doc/index.md>
|
||||
|
||||
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/<application UUID>/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.
|
||||
262
plugins/cordova-plugin-file-transfer/doc/es/index.md
Normal file
262
plugins/cordova-plugin-file-transfer/doc/es/index.md
Normal file
@@ -0,0 +1,262 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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.
|
||||
270
plugins/cordova-plugin-file-transfer/doc/fr/README.md
Normal file
270
plugins/cordova-plugin-file-transfer/doc/fr/README.md
Normal file
@@ -0,0 +1,270 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
Documentation du plugin : <doc/index.md>
|
||||
|
||||
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.
|
||||
261
plugins/cordova-plugin-file-transfer/doc/fr/index.md
Normal file
261
plugins/cordova-plugin-file-transfer/doc/fr/index.md
Normal file
@@ -0,0 +1,261 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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.
|
||||
311
plugins/cordova-plugin-file-transfer/doc/it/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/it/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
Documentazione plugin: <doc/index.md>
|
||||
|
||||
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/<application UUID>/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()`.
|
||||
302
plugins/cordova-plugin-file-transfer/doc/it/index.md
Normal file
302
plugins/cordova-plugin-file-transfer/doc/it/index.md
Normal file
@@ -0,0 +1,302 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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()`.
|
||||
311
plugins/cordova-plugin-file-transfer/doc/ja/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/ja/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
プラグインのマニュアル: <doc/index.md>
|
||||
|
||||
このプラグインは、アップロードし、ファイルをダウンロードすることができます。
|
||||
|
||||
このプラグインでは、グローバル `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/<application UUID>/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()` メソッドの絶対ファイル パスの代わりに使用できます。
|
||||
302
plugins/cordova-plugin-file-transfer/doc/ja/index.md
Normal file
302
plugins/cordova-plugin-file-transfer/doc/ja/index.md
Normal file
@@ -0,0 +1,302 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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()` メソッドの絶対ファイル パスの代わりに使用できます。
|
||||
311
plugins/cordova-plugin-file-transfer/doc/ko/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/ko/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
플러그인 문서: <doc/index.md>
|
||||
|
||||
이 플러그인을 사용 하면 업로드 및 다운로드 파일 수 있습니다.
|
||||
|
||||
이 플러그인 글로벌 `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/<application UUID>/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()` 방법에서 절대 파일 경로 대신 사용할 수 있습니다.
|
||||
302
plugins/cordova-plugin-file-transfer/doc/ko/index.md
Normal file
302
plugins/cordova-plugin-file-transfer/doc/ko/index.md
Normal file
@@ -0,0 +1,302 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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()` 방법에서 절대 파일 경로 대신 사용할 수 있습니다.
|
||||
311
plugins/cordova-plugin-file-transfer/doc/pl/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/pl/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
Plugin dokumentacja: <doc/index.md>
|
||||
|
||||
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/<application UUID>/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.
|
||||
302
plugins/cordova-plugin-file-transfer/doc/pl/index.md
Normal file
302
plugins/cordova-plugin-file-transfer/doc/pl/index.md
Normal file
@@ -0,0 +1,302 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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.
|
||||
290
plugins/cordova-plugin-file-transfer/doc/ru/index.md
Normal file
290
plugins/cordova-plugin-file-transfer/doc/ru/index.md
Normal file
@@ -0,0 +1,290 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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()` методы.
|
||||
311
plugins/cordova-plugin-file-transfer/doc/zh/README.md
Normal file
311
plugins/cordova-plugin-file-transfer/doc/zh/README.md
Normal file
@@ -0,0 +1,311 @@
|
||||
<!--
|
||||
# license: Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
-->
|
||||
|
||||
# cordova-plugin-file-transfer
|
||||
|
||||
[](https://travis-ci.org/apache/cordova-plugin-file-transfer)
|
||||
|
||||
外掛程式檔: <doc/index.md>
|
||||
|
||||
這個外掛程式允許你上傳和下載檔案。
|
||||
|
||||
這個外掛程式定義全域 `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/<application UUID>/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()` 兩種方法中的絕對檔路徑位置。
|
||||
302
plugins/cordova-plugin-file-transfer/doc/zh/index.md
Normal file
302
plugins/cordova-plugin-file-transfer/doc/zh/index.md
Normal file
@@ -0,0 +1,302 @@
|
||||
<!---
|
||||
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.
|
||||
-->
|
||||
|
||||
# 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/<application UUID>/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()` 兩種方法中的絕對檔路徑位置。
|
||||
Reference in New Issue
Block a user