Gathering detailed insights and metrics for cordova-plugin-file-transfer-ks
Gathering detailed insights and metrics for cordova-plugin-file-transfer-ks
npm install cordova-plugin-file-transfer-ks
Typescript
Module System
Node Version
NPM Version
74.2
Supply Chain
98.9
Quality
75.2
Maintenance
100
Vulnerability
87.6
License
JavaScript (57.05%)
Java (22.82%)
Objective-C (20.13%)
Love this project? Help keep it running — sponsor us today! 🚀
Total Downloads
200
Last Day
1
Last Week
4
Last Month
8
Last Year
39
599 Stars
538 Commits
889 Forks
60 Watching
18 Branches
105 Contributors
Latest Version
2.0.0-dev
Package Id
cordova-plugin-file-transfer-ks@2.0.0-dev
Unpacked Size
208.92 kB
Size
46.61 kB
File Count
17
NPM Version
6.14.8
Node Version
14.15.0
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
300%
4
Compared to previous week
Last month
300%
8
Compared to previous month
Last year
-41.8%
39
Compared to previous year
1
With the new features introduced in the Fetch API and the XMLHttpRequest, this plugin may not be needed any more for your use case. For small file transfers, you probably won't require this plugin. But, if you plan to handle large downloads, suffering from slow saving, timeouts, or crashes, this plugin is better suited for your use case over the Fetch API or the XMLHttpRequest.
Migrating from this plugin to using the new features of XMLHttpRequest, is explained in this Cordova blog post.
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.
1document.addEventListener("deviceready", onDeviceReady, false); 2function onDeviceReady() { 3 console.log(FileTransfer); 4}
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
1cordova plugin add cordova-plugin-file-transfer
The FileTransfer
object provides a way to upload files using an HTTP
multi-part POST or PUT request, and to download files.
ProgressEvent
whenever a new chunk of data is transferred. (Function)upload: Sends a file to a server.
download: Downloads a file from server.
abort: Aborts an in-progress transfer.
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 a FileTransferError
object. (Function)
options: Optional parameters (Object). Valid keys:
file
. (DOMString)image.jpg
. (DOMString)PUT
or POST
. Defaults to POST
. (DOMString)image/jpeg
. (DOMString)true
. (Boolean)trustAllHosts: Optional parameter, defaults to false
. If set to true
, it accepts all security certificates. Not recommended for production use. Supported on iOS. (boolean)
1// !! Assumes variable fileURL contains a valid URL to a text file on the device, 2// for example, cdvfile://localhost/persistent/path/to/file.txt 3 4var win = function (r) { 5 console.log("Code = " + r.responseCode); 6 console.log("Response = " + r.response); 7 console.log("Sent = " + r.bytesSent); 8} 9 10var fail = function (error) { 11 alert("An error has occurred: Code = " + error.code); 12 console.log("upload error source " + error.source); 13 console.log("upload error target " + error.target); 14} 15 16var options = new FileUploadOptions(); 17options.fileKey = "file"; 18options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); 19options.mimeType = "text/plain"; 20 21var params = {}; 22params.value1 = "test"; 23params.value2 = "param"; 24 25options.params = params; 26 27var ft = new FileTransfer(); 28ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
1function win(r) { 2 console.log("Code = " + r.responseCode); 3 console.log("Response = " + r.response); 4 console.log("Sent = " + r.bytesSent); 5} 6 7function fail(error) { 8 alert("An error has occurred: Code = " + error.code); 9 console.log("upload error source " + error.source); 10 console.log("upload error target " + error.target); 11} 12 13var uri = encodeURI("http://some.server.com/upload.php"); 14 15var options = new FileUploadOptions(); 16options.fileKey="file"; 17options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1); 18options.mimeType="text/plain"; 19 20var headers={'headerParam':'headerValue', 'headerParam2':'headerValue2'}; 21 22options.headers = headers; 23 24var ft = new FileTransfer(); 25var progressValue = 0; 26ft.onprogress = function(progressEvent) { 27 if (progressEvent.lengthComputable) { 28 // Calculate the percentage 29 progressValue = progressEvent.loaded / progressEvent.total; 30 } else { 31 progressValue++; 32 } 33 34 // Display percentage in the UI 35 document.getElementByID('progress-value').innerHTML = progressValue; 36}; 37ft.upload(fileURL, uri, win, fail, options);
A FileUploadResult
object is passed to the success callback of the
FileTransfer
object's upload()
method.
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)
Does not support responseCode
or bytesSent
.
Does not support uploads of an empty file with chunkedMode=true and multipartMode=false
.
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.
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 a FileTransferError
object. (Function)
trustAllHosts: Optional parameter, defaults to false
. If set to true
, 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).
1// !! Assumes variable fileURL contains a valid URL to a path on the device, 2// for example, cdvfile://localhost/persistent/path/to/downloads/ 3 4var fileTransfer = new FileTransfer(); 5var uri = encodeURI("http://some.server.com/download.php"); 6 7fileTransfer.download( 8 uri, 9 fileURL, 10 function(entry) { 11 console.log("download complete: " + entry.toURL()); 12 }, 13 function(error) { 14 console.log("download error source " + error.source); 15 console.log("download error target " + error.target); 16 console.log("download error code" + error.code); 17 }, 18 false, 19 { 20 headers: { 21 "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" 22 } 23 } 24);
Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR
.
1// !! Assumes variable fileURL contains a valid URL to a text file on the device, 2// for example, cdvfile://localhost/persistent/path/to/file.txt 3 4var win = function(r) { 5 console.log("Should not be called."); 6} 7 8var fail = function(error) { 9 // error.code == FileTransferError.ABORT_ERR 10 alert("An error has occurred: Code = " + error.code); 11 console.log("upload error source " + error.source); 12 console.log("upload error target " + error.target); 13} 14 15var options = new FileUploadOptions(); 16options.fileKey="file"; 17options.fileName="myphoto.jpg"; 18options.mimeType="image/jpeg"; 19 20var ft = new FileTransfer(); 21ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options); 22ft.abort();
A FileTransferError
object is passed to an error callback when an error occurs.
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)
exception is never defined.
FileTransferError.FILE_NOT_FOUND_ERR
FileTransferError.INVALID_URL_ERR
FileTransferError.CONNECTION_ERR
FileTransferError.ABORT_ERR
FileTransferError.NOT_MODIFIED_ERR
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.
Use the File-Transfer plugin to upload and download files. In these examples, we demonstrate several tasks like:
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.
1window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) { 2 3 console.log('file system open: ' + fs.name); 4 5 // Make sure you add the domain name to the Content-Security-Policy <meta> element. 6 var url = 'http://cordova.apache.org/static/img/cordova_bot.png'; 7 // Parameters passed to getFile create a new file or return the file if it already exists. 8 fs.root.getFile('downloaded-image.png', { create: true, exclusive: false }, function (fileEntry) { 9 download(fileEntry, url, true); 10 11 }, onErrorCreateFile); 12 13}, onErrorLoadFs);
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.
1function download(fileEntry, uri, readBinaryData) { 2 3 var fileTransfer = new FileTransfer(); 4 var fileURL = fileEntry.toURL(); 5 6 fileTransfer.download( 7 uri, 8 fileURL, 9 function (entry) { 10 console.log("Successful download..."); 11 console.log("download complete: " + entry.toURL()); 12 if (readBinaryData) { 13 // Read the file... 14 readBinaryFile(entry); 15 } 16 else { 17 // Or just display it. 18 displayImageByFileURL(entry); 19 } 20 }, 21 function (error) { 22 console.log("download error source " + error.source); 23 console.log("download error target " + error.target); 24 console.log("upload error code" + error.code); 25 }, 26 null, // or, pass false 27 { 28 //headers: { 29 // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" 30 //} 31 } 32 ); 33}
If you just need to display the image, take the FileEntry to call its toURL() function.
1function displayImageByFileURL(fileEntry) { 2 var elem = document.getElementById('imageElement'); 3 elem.src = fileEntry.toURL(); 4}
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.
1function readBinaryFile(fileEntry) {
2 fileEntry.file(function (file) {
3 var reader = new FileReader();
4
5 reader.onloadend = function() {
6
7 console.log("Successful file read: " + this.result);
8 // displayFileData(fileEntry.fullPath + ": " + this.result);
9
10 var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
11 displayImage(blob);
12 };
13
14 reader.readAsArrayBuffer(file);
15
16 }, onErrorReadFile);
17}
Once you read the file successfully, you can create a DOM URL string using createObjectURL
, and then display the image.
1function displayImage(blob) {
2
3 // Note: Use window.URL.revokeObjectURL when finished with image.
4 var objURL = window.URL.createObjectURL(blob);
5
6 // Displays image if result is a valid DOM string for an image.
7 var elem = document.getElementById('imageElement');
8 elem.src = objURL;
9}
As you saw previously, you can call FileEntry.toURL() instead to just display the downloaded image (skip the file read).
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.
1function onUploadFile() {
2 window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
3
4 console.log('file system open: ' + fs.name);
5 var fileName = "uploadSource.txt";
6 var dirEntry = fs.root;
7 dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
8
9 // Write something to the file before uploading it.
10 writeFile(fileEntry);
11
12 }, onErrorCreateFile);
13
14 }, onErrorLoadFs);
15}
In this example, create some simple content, and then call the app's upload function.
1function writeFile(fileEntry, dataObj) {
2 // Create a FileWriter object for our FileEntry (log.txt).
3 fileEntry.createWriter(function (fileWriter) {
4
5 fileWriter.onwriteend = function () {
6 console.log("Successful file write...");
7 upload(fileEntry);
8 };
9
10 fileWriter.onerror = function (e) {
11 console.log("Failed file write: " + e.toString());
12 };
13
14 if (!dataObj) {
15 dataObj = new Blob(['file data to upload'], { type: 'text/plain' });
16 }
17
18 fileWriter.write(dataObj);
19 });
20}
Forward the FileEntry object to the upload function. To perform the actual upload, use the upload function of the FileTransfer object.
1function upload(fileEntry) { 2 // !! Assumes variable fileURL contains a valid URL to a text file on the device, 3 var fileURL = fileEntry.toURL(); 4 5 var success = function (r) { 6 console.log("Successful upload..."); 7 console.log("Code = " + r.responseCode); 8 // displayFileData(fileEntry.fullPath + " (content uploaded to server)"); 9 } 10 11 var fail = function (error) { 12 alert("An error has occurred: Code = " + error.code); 13 } 14 15 var options = new FileUploadOptions(); 16 options.fileKey = "file"; 17 options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1); 18 options.mimeType = "text/plain"; 19 20 var params = {}; 21 params.value1 = "test"; 22 params.value2 = "param"; 23 24 options.params = params; 25 26 var ft = new FileTransfer(); 27 // SERVER must be a URL that can handle the request, like 28 // http://some.server.com/upload.php 29 ft.upload(fileURL, encodeURI(SERVER), success, fail, options); 30};
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.
1function download(fileEntry, uri) { 2 3 var fileTransfer = new FileTransfer(); 4 var fileURL = fileEntry.toURL(); 5 6 fileTransfer.download( 7 uri, 8 fileURL, 9 function (entry) { 10 console.log("Successful download..."); 11 console.log("download complete: " + entry.toURL()); 12 readFile(entry); 13 }, 14 function (error) { 15 console.log("download error source " + error.source); 16 console.log("download error target " + error.target); 17 console.log("upload error code" + error.code); 18 }, 19 null, // or, pass false 20 { 21 //headers: { 22 // "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" 23 //} 24 } 25 ); 26}
In the readFile function, call the readAsText
method of the FileReader object.
1function readFile(fileEntry) { 2 fileEntry.file(function (file) { 3 var reader = new FileReader(); 4 5 reader.onloadend = function () { 6 7 console.log("Successful file read: " + this.result); 8 // displayFileData(fileEntry.fullPath + ": " + this.result); 9 10 }; 11 12 reader.readAsText(file); 13 14 }, onErrorReadFile); 15}
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 23/28 approved changesets -- score normalized to 8
Reason
6 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More