bambaniasz
bambaniasz

Reputation: 321

Ionic 3 - download a file to directory

I have the similar problem like here: How to download file to Download's directory with Ionic Framework?

I got success alert after download but I can't see the file in an Android file explorer under the path displayed after succeed download: file:///data/user/0/io.ionic.fileTest/image.jpg

My code:

download(){

const fileTransfer: FileTransferObject = this.transfer.create();
const url = "http://cdna.allaboutvision.com/i/conditions-2016/heterochromia-kate-bosworth-660x660-with-credit.jpg";

fileTransfer.download(url, this.file.dataDirectory + 'laska.jpg', true).then((entry) => {

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

}, (error) => {

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

Could I somehow manage to save this file in e.g "Download" folder or "Documents"? I also tried changing destination path to:

cordova.file.externalRootDirectory + '/Download/'

In that case, I received error 1.

In many examples I see people use window.requestFileSystem() but it looks like the window doesn't have this method for me. I use visual studio code and ionic 3.

Upvotes: 1

Views: 4644

Answers (2)

bambaniasz
bambaniasz

Reputation: 321

Working code that downloads a file to Downloads directory:

downloadFile() {
  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").then()
}

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();
            }
          });
      }
    });
}

Upvotes: 0

Utpaul
Utpaul

Reputation: 2007

You got little bit mistake in fileTransfer.download

instead of this.file.applicationStorageDirectory use this.file.dataDirectory

Upvotes: 1

Related Questions