Issue: Permission Denied When Downloading Files in Ionic Capacitor App
Hi everyone,
I’m currently working on an Ionic Capacitor app and facing an issue when trying to download a file from external storage. Despite implementing the necessary permissions, I’m getting a “Permission Denied” error.
Here’s the method I’m using for downloading files:
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
import { File } from "@ionic-native/file/ngx";
async download(url) {
this.requestWritePermission();
const loading = await this.loadingCtrl.create({
message: 'Downloading file...'
});
await loading.present();
const filename = url.substring(url.lastIndexOf('/') + 1);
const downloadFolder = this.platform.is('android') ? this.file.externalRootDirectory + 'download' : '';
const request: DownloadRequest = {
uri: url,
title: filename,
description: 'Downloading file...',
mimeType: '',
visibleInDownloadsUi: true,
notificationVisibility: NotificationVisibility.VisibleNotifyCompleted,
destinationUri: downloadFolder + '/' + filename,
};
this.downloader.download(request)
.then((location: string) => this.presentToastDownload('File downloaded at: ' + location, location))
.catch((error: any) => console.error(error));
loading.dismiss();
}
requestWritePermission() {
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.MANAGE_EXTERNAL_STORAGE).then(
(result) => {
if (result.hasPermission) {
// Permission granted
} else {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.MANAGE_EXTERNAL_STORAGE).then(
(result) => {
if (result.hasPermission) {
// Permission granted
} else {
console.error('Write permission denied by the user.');
}
},
(error) => {
console.error('Error requesting write permission:', error);
}
);
}
},
(error) => {
console.error('Error checking write permission status:', error);
}
);
}
async presentToastdownload(msg, location) {
const toast = await this.toastController.create({
message: "file downloaded",
icon: 'checkmark-done',
duration: 3000,
cssClass: 'success_alert',
buttons: [
{
text: 'Open',
handler: () => {
this.openfile(location);
}
}
]
});
toast.present();
}
openfile(path) {
this.fileOpener.open(path, null)
.then(() => {
})
.catch(e => {
});
}