The file transfer API can be leveraged for the FileTransfer
object to either download a file
from a remote server via the download
method or upload a file from the local storage using the upload
method. Any file transfer
operation that has started can also be canceled at any time before it has finished using the
cancel
method on the FileTransferTask
object.
The download
method allows a user to specify the following
parameters:
the URL pointing to the file on a remote server to be downloaded,
a file path to where it is to be saved locally,
optional transfer parameters such as credentials, map of query parameters, map of header names/values and whether to accept all security certificates.
callbacks to respond in case of failure, canceling, success or current progress of the operation.
The upload
method allows a user to specify the following
parameters:
a path to the local file that is to be uploaded to the remote server,
a URL address pointing to the server, to which the file is to be uploaded,
optional transfer parameters such as credentials, file key, file name, MIME type, map of parameter names/values, map of header names/values and whether to accept all security certificates,
callbacks to respond in case of success, failure, canceling or current progress of the operation.
File transfer processes are active only while the application is running. Transferring a file of the same name to the same location results in the existing file being overwritten.
The following example illustrates the use of the file transfer API.
var options = { credentials: "admin:secret", headers: { "sample-header": "sample-value", "sample-multi-header": ["sample-multi-value1","sample-multi-value2"] }, params: { "paramA": "valueA", "paramB": "valueB" } } var callback = { onSuccess: function (entry) { console.log("onSuccess " + JSON.stringify(entry)); entry.file(function (file) { var reader = new FileReader(); reader.onload = function () { console.log("content = " + reader.result); }; try { reader.readAsText(file); } catch (e) { console.log("reader.readAsText error: " + JSON.stringify(e)); } }, function (err) { console.log("file error: " + JSON.stringify(err)); }); }, onProgress: function (progress) { console.log("onProgress " + progress); }, onCancel: function () { console.log("onCancel"); }, onFailure: function (data) { console.log("onFailure " + JSON.stringify(data)); } }; requestFileSystem(window.PERSISTENT, 60 * 1024 * 1024, function (fs) { fs.root.getFile("file.txt", {create: true}, function (entry) { launchbox.FileTransfer.download("http://example.com/file.txt", entry.toURL(), options, callback); }, function (err) { console.log("getFile error: " + JSON.stringify(err)); }); }, function (err) { console.log("requestFileSystem error: " + JSON.stringify(err)); });