Ionic 3 - 将文件下载到目录

时间:2018-03-23 08:07:09

标签: javascript android cordova ionic-framework ionic3

我遇到类似的问题: How to download file to Download's directory with Ionic Framework?

下载后我获得了成功警报,但在成功下载后显示的路径下,我无法在Android文件资源管理器中看到该文件:file:///data/user/0/io.ionic.fileTest/image .JPG

我的代码:

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

我能以某种方式设法将此文件保存在例如"下载"文件夹或"文件"?我也尝试将目标路径更改为:

cordova.file.externalRootDirectory + '/Download/'

在这种情况下,我收到错误1。

在许多例子中,我看到人们使用        window.requestFileSystem() 但看起来窗口对我来说没有这种方法。我使用visual studio代码和离子3。

2 个答案:

答案 0 :(得分:1)

你在fileTransfer.download

中犯了一点错误

而不是this.file.applicationStorageDirectory使用this.file.dataDirectory

答案 1 :(得分:0)

将文件下载到Downloads目录的工作代码:

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