Saving file to Downloads directory using Ionic 3

限于喜欢 提交于 2019-12-06 02:01:22

问题


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.


回答1:


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



回答2:


To download the File to the Download directory you need to use Cordova File and FileTransfer Plugins.

import { File } from '@ionic-native/file';
import { FileTransfer } from '@ionic-native/file-transfer';

constructor(private transfer: FileTransfer) { }

fileTransfer: FileTransferObject = this.transfer.create();

//Use your File Url and name

downloadFile(file) {
  // Some Loading
  this.fileTransfer.download(url, this.file.externalRootDirectory + 
  '/Download/' + file).then(response => {
  console.log(response);
  this.dismissLoading();
  this.presentToast('File has been downloaded to the Downloads folder. View 
  it..')
  })
  .catch(err => {
    this.dismissLoading();
    console.log(err)
  });
}

Hope it helps.




回答3:


import { File } from '@ionic-native/file';
import { FileTransfer } from '@ionic-native/file-transfer';
constructor(private file: File, private transfer: FileTransfer){}

let link = 'url_to_download_file';
let path = '';
let dir_name = 'Download'; // directory to download - you can also create new directory
let file_name = 'file.txt'; //any file name you like

const fileTransfer: FileTransferObject = this.transfer.create();
let result = this.file.createDir(this.file.externalRootDirectory, dir_name, true);
result.then((resp) => {
  path = resp.toURL();
  console.log(path);
  fileTransfer.download(link, path + file_name).then((entry) => {
    console.log('download complete: ' + entry.toURL());
  }, (error) => {
    console.log(error)
  });
}, (err) => {
  console.log('error on creating path : ' + err);
});



回答4:


I know this is late, but I've always had issues with the FileTransfer plugin. Maybe it is just me. I've instead had success with the writeFile() method of the File plugin.

I'm still working on iOS, but for Android here is what I have:

import { File } from "@ionic-native/file";

constructor(private fileSystem: File) {}

Then, in whatever function you have the logic to save the file, we have:

let path = this.fileSystem.externalRootDirectory + '/Download/'; // for Android
let filename = 'myNewFile.pdf';
this.fileSystem.writeFile(path, filename, File, { replace: true }).then(() => {
        this.toastCtrl.showToast('File has been downloaded. Please check your downloads folder.');
    }, (err) => {
        alert("Sorry. An error occurred downloading the file: " + err);
    }
);

As I said, I'm still looking out for what path to use for iOS. And I'm still wondering how to pop up the notification that usually comes up when a download actually goes to the download folder. But at least I am able to save directly in the download folder of Android.




回答5:


This code - ionic 3 capacitor - from josh morony takes a photo from the tmp directory and writes to the Document directory in this section using the FileSystem API the retrieves and manipulates the path

        Filesystem.writeFile({
            data: result.data,
            path: fileName,
            directory: FilesystemDirectory.Data
        })



getFromPhotos() {

  let options = {
  resultType: CameraResultType.Uri
  };

  Camera.getPhoto(options).then(

(photo) => {

    Filesystem.readFile({
        path: photo.path
    }).then((result) => {

        // let date = new Date(),
        // time = date.getTime(),
        time = 'bilder',
            fileName = time + '.jpeg';

        Filesystem.writeFile({
            data: result.data,
            path: fileName,
            directory: FilesystemDirectory.Data
        }).then((result) => {
            Filesystem.getUri({
                directory: FilesystemDirectory.Data,
                path: fileName
            }).then((result) => {
                console.log(result);
              let path = result.uri.replace('file://', '_capacitor_');
              this.image = this.sanitizer.bypassSecurityTrustResourceUrl(path);
            }, (err) => {
                console.log(err);
            });

        }, (err) => {
            console.log(err);
        });

    }, (err) => {
        console.log(err);
    });

}, (err) => {
    console.log(err);
}

);

}

In ionic 3 you have to use the cordova File plugin - please google. It is pretty straight forward to understand: you define the original directory where the file is, the original name of the file, the target directory, and a new name for the file inside that function. The principle is the same.



来源:https://stackoverflow.com/questions/49051139/saving-file-to-downloads-directory-using-ionic-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!