Installations
npm install cordova-plugin-ns0m-file-transfer
Developer Guide
Typescript
Yes
Module System
N/A
Node Version
18.17.1
NPM Version
9.6.7
Score
75.2
Supply Chain
98.6
Quality
75.5
Maintenance
100
Vulnerability
88
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (62.55%)
Java (19.9%)
Objective-C (17.55%)
Developer
ns0m
Download Statistics
Total Downloads
17,536
Last Day
2
Last Week
31
Last Month
161
Last Year
6,031
GitHub Statistics
549 Commits
1 Forks
2 Watching
16 Branches
1 Contributors
Package Meta Information
Latest Version
2.0.0-8
Package Id
cordova-plugin-ns0m-file-transfer@2.0.0-8
Unpacked Size
209.11 kB
Size
46.36 kB
File Count
17
NPM Version
9.6.7
Node Version
18.17.1
Publised On
25 Aug 2023
Total Downloads
Cumulative downloads
Total Downloads
17,536
Last day
-60%
2
Compared to previous day
Last week
-45.6%
31
Compared to previous week
Last month
11%
161
Compared to previous month
Last year
-21.3%
6,031
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
1
Publication-only version of the apache/cordova-plugin-file-transfer package with some early fixes.
cordova plugin add cordova-plugin-ns0m-file-transfer@2.0.0-8
title: File Transfer description: Upload and download files.
cordova-plugin-file-transfer
Usage notice
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.
Description
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
Installation
1cordova plugin add cordova-plugin-file-transfer
Supported Platforms
- Android
- Browser
- iOS
- Windows
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
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);
Example with Upload Headers and Progress Events (Android and iOS only)
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);
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
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);
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
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();
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.
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).
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.
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};
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.
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 dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-npm.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/ns0m/cordova-plugin-ns0m-file-transfer/publish-npm.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-npm.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/ns0m/cordova-plugin-ns0m-file-transfer/publish-npm.yml/master?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/publish-npm.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 1 are checked with a SAST tool
Reason
12 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-wm7h-9275-46v2
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m
- Warn: Project is vulnerable to: GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-6xwr-q98w-rvg7
Score
2.7
/10
Last Scanned on 2025-01-27
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