Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving file to Downloads directory using Ionic 3

i know this link: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/#where-to-store-files

but i would like to save the file in Downloads directory. Is this possible to save the file in any path using Ionic? If so, please, share the example.

Here's the code:

downloadImage(image) {

this.platform.ready().then(() => {

  const fileTransfer: TransferObject = this.transfer.create();

  const imageLocation = `${cordova.file.applicationDirectory}www/assets/img/${image}`;

  fileTransfer.download(imageLocation, cordova.file.externalDataDirectory + image).then((entry) => {

    const alertSuccess = this.alertCtrl.create({
      title: `Download Succeeded!`,
      subTitle: `${image} was successfully downloaded to: ${entry.toURL()}`,
      buttons: ['Ok']
    });

    alertSuccess.present();

  }, (error) => {

    const alertFailure = this.alertCtrl.create({
      title: `Download Failed!`,
      subTitle: `${image} was not successfully downloaded. Error code: ${error.code}`,
      buttons: ['Ok']
    });

    alertFailure.present();

  });

});

}

Basically I want save the file in location that is visible to the user.

like image 306
bambaniasz Avatar asked Mar 01 '18 13:03

bambaniasz


1 Answers

the problem was lack of permission. Here is the working code that can download file to downloads directory:

async downloadFile() {
  await this.fileTransfer.download("https://cdn.pixabay.com/photo/2017/01/06/23/21/soap-bubble-1959327_960_720.jpg", this.file.externalRootDirectory + 
  '/Download/' + "soap-bubble-1959327_960_720.jpg");
}

getPermission() {
  this.androidPermissions.hasPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
    .then(status => {
      if (status.hasPermission) {
        this.downloadFile();
      } 
      else {
        this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
          .then(status => {
            if(status.hasPermission) {
              this.downloadFile();
            }
          });
      }
    });
}
like image 121
bambaniasz Avatar answered Oct 19 '22 03:10

bambaniasz