Skip to content

Instantly share code, notes, and snippets.

@Kraloz
Created October 6, 2020 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kraloz/4e3b1d7a0c7c736b4f1a03a59c50d776 to your computer and use it in GitHub Desktop.
Save Kraloz/4e3b1d7a0c7c736b4f1a03a59c50d776 to your computer and use it in GitHub Desktop.
const fileDownloadManager = {
initDownload({ endpoint, filename }) {
fileDownloadManager.endpoint = endpoint
fileDownloadManager.filename = filename
const permissions = window.cordova.plugins.permissions
permissions.checkPermission(
permissions.READ_EXTERNAL_STORAGE,
fileDownloadManager.checkPermissionCallback,
null
)
},
downloadFile() {
// let filePath = cordova.file.externalRootDirectory + 'download/' + fileDownloadManager.filename
let filePath = cordova.file.dataDirectory + 'download/' + fileDownloadManager.filename
let filePath = encodeURI(filePath)
let fileTransfer = new window.FileTransfer()
let uri = encodeURI(decodeURIComponent(fileDownloadManager.endpoint))
// Downloading the file
fileTransfer.download(uri, filePath,
function (entry) {
console.log('Successfully downloaded file, full path is ' + entry.fullPath)
console.log(entry)
},
function (error) {
console.log('error')
console.log(error)
},
false
)
},
// Checking for permissions
checkPermissionCallback(status) {
const permissions = window.cordova.plugins.permissions
console.log('checking permissions')
console.log(status)
if (!status.hasPermission) {
// Asking permission to the user
permissions.requestPermission(
permissions.READ_EXTERNAL_STORAGE,
function (status) {
if (!status.hasPermission) {
fileDownloadManager.onPermissionErrorCallback()
} else {
// proceed with downloading
fileDownloadManager.downloadFile()
}
},
fileDownloadManager.onPermissionErrorCallback)
} else {
fileDownloadManager.downloadFile()
}
},
onPermissionErrorCallback() {
console.warn('Storage permission is not turned on')
fileDownloadManager.endpoint = null
fileDownloadManager.filename = null
}
}
export default fileDownloadManager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment