title: File Transfer description: Upload and download files.
AppVeyor | Travis CI |
---|---|
mes-plugin-file-transfer
This plugin allows you to upload and download files.
This plugin defines global FileTransfer
, FileUploadOptions
constructors. Although in the global scope, they are not available until after the deviceready
event.
document; { console;}
To get a few ideas, check out the sample at the bottom of this page.
Report issues with this plugin on the Apache Cordova issue tracker
Deprecated
With the new features introduced in XMLHttpRequest, this plugin is not needed any more. Migrating from this plugin to using the new features of XMLHttpRequest, is explained in this Cordova blog post.
Installation
cordova plugin add mes-plugin-file-transfer
Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS**
- iOS
- Windows Phone 7 and 8*
- Windows
* Do not support onprogress
nor abort()
** Do not support onprogress
FileTransfer
The FileTransfer
object provides a way to upload files using an HTTP
multi-part POST or PUT request, and to download files.
Properties
- onprogress: Called with a
ProgressEvent
whenever a new chunk of data is transferred. (Function)
Methods
-
upload: Sends a file to a server.
-
download: Downloads a file from server.
-
abort: Aborts an in-progress transfer.
upload
Parameters:
-
fileURL: Filesystem URL representing the file on the device or a data URI. For backwards compatibility, this can also be the full path of the file on the device. (See Backwards Compatibility Notes below)
-
server: URL of the server to receive the file, as encoded by
encodeURI()
. -
successCallback: A callback that is passed a
FileUploadResult
object. (Function) -
errorCallback: A callback that executes if an error occurs retrieving the
FileUploadResult
. Invoked with aFileTransferError
object. (Function) -
options: Optional parameters (Object). Valid keys:
- fileKey: The name of the form element. Defaults to
file
. (DOMString) - fileName: The file name to use when saving the file on the server. Defaults to
image.jpg
. (DOMString) - httpMethod: The HTTP method to use - either
PUT
orPOST
. Defaults toPOST
. (DOMString) - mimeType: The mime type of the data to upload. Defaults to
image/jpeg
. (DOMString) - params: A set of optional key/value pairs to pass in the HTTP request. (Object, key/value - DOMString)
- chunkedMode: Whether to upload the data in chunked streaming mode. Defaults to
true
. (Boolean) - headers: A map of header name/header values. Use a hash to specify one or more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used. (Object)
- fileKey: The name of the form element. Defaults to
-
trustAllHosts: Optional parameter, defaults to
false
. If set totrue
, it accepts all security certificates. Not recommended for production use. Supported on iOS. (boolean)
Example
// !! Assumes variable fileURL contains a valid URL to a text file on the device,// for example, cdvfile://localhost/persistent/path/to/file.txt var { console; console; console;} var { ; console; console;} var options = ;optionsfileKey = "file";optionsfileName = fileURL;optionsmimeType = "text/plain"; var params = {};paramsvalue1 = "test";paramsvalue2 = "param"; optionsparams = params; var ft = ;ft;
Example with Upload Headers and Progress Events (Android and iOS only)
{ console; console; console;} { ; console; console;} var uri = ; var options = ;optionsfileKey="file";optionsfileName=fileURL;optionsmimeType="text/plain"; var headers='headerParam':'headerValue' 'headerParam2':'headerValue2'; optionsheaders = headers; var ft = ;ft { if progressEventlengthComputable loadingStatus; else loadingStatus; };ft;
FileUploadResult
A FileUploadResult
object is passed to the success callback of the
FileTransfer
object's upload()
method.
Properties
-
bytesSent: The number of bytes sent to the server as part of the upload. (long)
-
responseCode: The HTTP response code returned by the server. (long)
-
response: The HTTP response returned by the server. (DOMString)
-
headers: The HTTP response headers by the server. (Object)
- Currently supported on iOS only.
iOS Quirks
-
Does not support
responseCode
orbytesSent
. -
Does not support uploads of an empty file with chunkedMode=true and
multipartMode=false
.
Browser Quirks
- withCredentials: boolean that tells the browser to set the withCredentials flag on the XMLHttpRequest
Windows Quirks
-
An option parameter with empty/null value is excluded in the upload operation due to the Windows API design.
-
chunkedMode is not supported and all uploads are set to non-chunked mode.
download
Parameters:
-
source: URL of the server to download the file, as encoded by
encodeURI()
. -
target: Filesystem url representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device. (See Backwards Compatibility Notes below)
-
successCallback: A callback that is passed a
FileEntry
object. (Function) -
errorCallback: A callback that executes if an error occurs when retrieving the
FileEntry
. Invoked with aFileTransferError
object. (Function) -
trustAllHosts: Optional parameter, defaults to
false
. If set totrue
, it accepts all security certificates. Not recommended for production use. Supported on iOS. (boolean) -
options: Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).
Example
// !! Assumes variable fileURL contains a valid URL to a path on the device,// for example, cdvfile://localhost/persistent/path/to/downloads/ var fileTransfer = ;var uri = ; fileTransfer;
WP8 Quirks
- Download requests is being cached by native implementation. To avoid caching, pass
if-Modified-Since
header to download method.
Browser Quirks
- withCredentials: boolean that tells the browser to set the withCredentials flag on the XMLHttpRequest
abort
Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR
.
Example
// !! Assumes variable fileURL contains a valid URL to a text file on the device,// for example, cdvfile://localhost/persistent/path/to/file.txt var { console;} var { // error.code == FileTransferError.ABORT_ERR ; console; console;} var options = ;optionsfileKey="file";optionsfileName="myphoto.jpg";optionsmimeType="image/jpeg"; var ft = ;ft;ft;
FileTransferError
A FileTransferError
object is passed to an error callback when an error occurs.
Properties
-
code: One of the predefined error codes listed below. (Number)
-
source: URL to the source. (String)
-
target: URL to the target. (String)
-
http_status: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number)
-
body Response body. This attribute is only available when a response is received from the HTTP connection. (String)
-
exception: Either e.getMessage or e.toString (String)
iOS Quirks
exception is never defined.
Constants
- 1 =
FileTransferError.FILE_NOT_FOUND_ERR
- 2 =
FileTransferError.INVALID_URL_ERR
- 3 =
FileTransferError.CONNECTION_ERR
- 4 =
FileTransferError.ABORT_ERR
- 5 =
FileTransferError.NOT_MODIFIED_ERR
Windows Quirks
- The plugin implementation is based on BackgroundDownloader/BackgroundUploader, which entails the latency issues on Windows devices (creation/starting of an operation can take up to a few seconds). You can use XHR or HttpClient as a quicker alternative for small downloads.
Backwards Compatibility Notes
Previous versions of this plugin would only accept device-absolute-file-paths as the source for uploads, or as the target for downloads. These paths would typically be of the form:
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
For backwards compatibility, these paths are still accepted, and if your application has recorded paths like these in persistent storage, then they can continue to be used.
These paths were previously exposed in the fullPath
property of FileEntry
and DirectoryEntry
objects returned by the File plugin. New versions of the File plugin however, no longer expose these paths to JavaScript.
If you are upgrading to a new (1.0.0 or newer) version of File, and you have previously been using entry.fullPath
as arguments to download()
or upload()
, then you will need to change your code to use filesystem URLs instead.
FileEntry.toURL()
and DirectoryEntry.toURL()
return a filesystem URL of the form:
cdvfile://localhost/persistent/path/to/file
which can be used in place of the absolute file path in both download()
and upload()
methods.
Sample: Download and Upload Files
Use the File-Transfer plugin to upload and download files. In these examples, we demonstrate several tasks like:
- Downloading a binary file to the application cache
- Uploading a file created in your application's root
- Downloading the uploaded file
Download a Binary File to the application cache
Use the File plugin with the File-Transfer plugin to provide a target for the files that you download (the target must be a FileEntry object). Before you download the file, create a DirectoryEntry object by using resolveLocalFileSystemURL
and calling fs.root
in the success callback. Use the getFile
method of DirectoryEntry to create the target file.
window;
Note For persistent storage, pass LocalFileSystem.PERSISTENT to requestFileSystem.
When you have the FileEntry object, download the file using the download
method of the FileTransfer object. The 3rd argument to the download
function of FileTransfer is the success callback, which you can use to call the app's readBinaryFile
function. In this code example, the entry
variable is a new FileEntry object that receives the result of the download operation.
{ var fileTransfer = ; var fileURL = fileEntry; fileTransfer;}
If you just need to display the image, take the FileEntry to call its toURL() function.
{ var elem = document; elemsrc = fileEntry;}
Depending on your app requirements, you may want to read the file. To support operations with binary files, FileReader supports two methods, readAsBinaryString
and readAsArrayBuffer
. In this example, use readAsArrayBuffer
and pass the FileEntry object to the method. Once you read the file successfully, construct a Blob object using the result of the read.
{ fileEntry;}
Once you read the file successfully, you can create a DOM URL string using createObjectURL
, and then display the image.
{ // Note: Use window.URL.revokeObjectURL when finished with image. var objURL = windowURL; // Displays image if result is a valid DOM string for an image. var elem = document; elemsrc = objURL;}
As you saw previously, you can call FileEntry.toURL() instead to just display the downloaded image (skip the file read).
Upload a File
When you upload a File using the File-Transfer plugin, use the File plugin to provide files for upload (again, they must be FileEntry objects). Before you can upload anything, create a file for upload using the getFile
method of DirectoryEntry. In this example, create the file in the application's cache (fs.root). Then call the app's writeFile function so you have some content to upload.
{ window;}
In this example, create some simple content, and then call the app's upload function.
{ // Create a FileWriter object for our FileEntry (log.txt). fileEntry;}
Forward the FileEntry object to the upload function. To perform the actual upload, use the upload function of the FileTransfer object.
{ // !! Assumes variable fileURL contains a valid URL to a text file on the device, var fileURL = fileEntry; var { console; console; // displayFileData(fileEntry.fullPath + " (content uploaded to server)"); } var { ; } var options = ; optionsfileKey = "file"; optionsfileName = fileURL; optionsmimeType = "text/plain"; var params = {}; paramsvalue1 = "test"; paramsvalue2 = "param"; optionsparams = params; var ft = ; // SERVER must be a URL that can handle the request, like // http://some.server.com/upload.php ft;};
Download the uploaded file
To download the image you just uploaded, you will need a valid URL that can handle the request, for example, http://some.server.com/download.php. Again, the success handler for the FileTransfer.download method receives a FileEntry object. The main difference here from previous examples is that we call FileReader.readAsText to read the result of the download operation, because we uploaded a file with text content.
{ var fileTransfer = ; var fileURL = fileEntry; fileTransfer;}
In the readFile function, call the readAsText
method of the FileReader object.
{ fileEntry;}