This plugin can be used to upload and download files.
Installing File Transfer Plugin:
To install this plugin into your application, run the following command:
cordova plugin add cordova-plugin-file-transfer
After installing the plugin, you need to create two buttons:
<button id = "uploadFile">Upload file</button>
<button id = "downloadFile">Download file</button>
Next, you need to add click events and callback functions on these buttons inside device ready:
document.getElementById("uploadFile").addEventListener("click", uploadFile);
document.getElementById("downloadFile").addEventListener("click", downloadFile);
Download function:
To download the file from server into device, we will create this function. It is defined in js file, when you click on download button, it is called.
function downloadFile() {
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://s14.postimg.org/i8qvaxyup/bitcoin1.jpg");
var fileURL = "///storage/emulated/0/DCIM/myFile";
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("download error code" + error.code);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}
here, uri is the download link from server and fileURI is file path to save into your device.
Upload Function:
upload function will upload file to the server. this function will be called when you click on the upload file button.
function uploadFile() {
var fileURL = "///storage/emulated/0/DCIM/myFile"
var uri = encodeURI("http://posttestserver.com/post.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.upload(fileURL, uri, onSuccess, onError, options);
function onSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function onError(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
0 Comment(s)