FileTransfer

FileTransfer is an object that allows you to upload files to a server or download files from a server.

Properties

  • onprogress: Called with a ProgressEvent whenever a new chunk of data is transferred. (Function)

Methods

  • upload: sends a file to a server.
  • download: downloads a file from server.
  • abort: Aborts an in-progress transfer.

Details

The FileTransfer object provides a way to upload files to a remote server using an HTTP multi-part POST request. Both HTTP and HTTPS protocols are supported. Optional parameters can be specified by passing a FileUploadOptions object to the upload method. On successful upload, the success callback will be called with a FileUploadResult object. If an error occurs, the error callback will be invoked with a FileTransferError object. It is also possible to download a file from remote and save it on the device (only iOS and Android).

Supported Platforms

  • Android
  • BlackBerry WebWorks (OS 5.0 and higher)
  • iOS
  • Windows Phone 7 and 8
  • Windows 8

upload

Parameters:

  • filePath - Full path of the file on the device
  • server - URL of the server to receive the file (must already be encoded using encodeURI())
  • successCallback - A callback that is called with a Metadata object. (Function)
  • errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileTransferError object. (Function)
  • options - Optional parameters such as file name and mimetype
  • trustAllHosts - Optional parameter, defaults to false. If set to true then it will accept all security certificates. This is useful as Android rejects self signed security certificates. Not recommended for production use. Supported on Android and iOS. (boolean)

Quick Example

// !! Assumes variable fileURI contains a valid URI to a text file on the device

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](../fileuploadoptions/fileuploadoptions.html)();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var params = {}; params.value1 = "test"; params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);

Full Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>File Transfer Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
    <script type="text/javascript" charset="utf-8">

        // Wait for Cordova to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready
        //
        function onDeviceReady() {

            // Retrieve image file location from specified source
            navigator.camera.getPicture(uploadPhoto,
                                        function(message) { alert('get picture failed'); },
                                        { quality: 50, 
                                        destinationType: navigator.camera.DestinationType.FILE_URI,
                                        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                                        );

        }

        function uploadPhoto(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = {};
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;

            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
        }

        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);
        }

        </script>
</head>
<body>
    <h1>Example</h1>
    <p>Upload File</p>
</body>
</html>

Setting Upload Headers

Supported on Android and 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=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var headers={'headerParam':'headerValue'};

options.headers = headers;

var ft = new FileTransfer();
ft.upload(fileURI, uri, win, fail, options);    

Android Quirks

If you experience problems uploading to a Nginx server then make sure you have the chunkedMode option set to false.

download

Parameters:

  • source - URL of the server to download the file (must already be encoded using encodeURI())
  • target - Full path of the file on the device
  • successCallback - A callback that is called with a FileEntry object. (Function)
  • errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileTransferError object. (Function)
  • trustAllHosts - Optional parameter, defaults to false. If set to true then it will accept all security certificates. This is useful as Android rejects self signed security certificates. Not recommended for production use. Supported on Android and iOS. (boolean)
  • options - Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).

Quick Example

// !! Assumes filePath is a valid path on the device

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");

fileTransfer.download(
    uri,
    filePath,
    function(entry) {
        console.log("download complete: " + entry.fullPath);
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("upload error code" + error.code);
    },
    false,
    {
        headers: {
            "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    }
);

abort

Aborts an in-progress transfer. The onerror callback will be called with a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.

Supported Platforms

  • Android
  • iOS

Quick Example

// !! Assumes variable fileURI contains a valid URI to a text file on the device

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](../fileuploadoptions/fileuploadoptions.html)();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var params = {};
params.value1 = "test";
params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
ft.abort(win, fail);

onprogress

Called with a ProgressEvent whenever a new chunk of data is transferred.

Supported Platforms

  • Android
  • iOS

Example

fileTransfer.onprogress = function(progressEvent) {
    if (progressEvent.lengthComputable) {
      loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
    } else {
      loadingStatus.increment();
    }
};
fileTransfer.download(...); // or fileTransfer.upload(...);

Quirks

  • On both Android an iOS, lengthComputable is false for downloads that use gzip encoding.