【问题标题】:Saving file to Downloads directory using Ionic 3使用 Ionic 3 将文件保存到下载目录
【发布时间】:2018-03-01 13:50:55
【问题描述】:

我知道这个链接:https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/#where-to-store-files

但我想将文件保存在下载目录中。这是否可以使用 Ionic 将文件保存在任何路径中?如果是这样,请分享示例。

代码如下:

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

  });

});

}

基本上我想将文件保存在用户可见的位置。

【问题讨论】:

    标签: android cordova ionic-framework ionic3


    【解决方案1】:

    问题是没有权限。这是可以将文件下载到下载目录的工作代码:

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

    【讨论】:

    • 我认为权限应该是 WRITE_EXTERNAL_STORAGE。
    • 如何使用 @ionic/vue 实现这个?谢谢
    【解决方案2】:

    要将文件下载到下载目录,您需要使用 Cordova FileFileTransfer 插件。

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

    希望对你有帮助。

    【讨论】:

    • 这段代码真的适合你吗?它不适合我。我无法在此目录中保存文件。我只能将文件保存在 file.dataDirectory 中。
    • 是的,它可以工作,并将文件保存在下载目录中。你安装了离子文件插件吗??
    • 是的,它出现在下载目录中,我已经对此进行了测试并在我的应用中实现了此代码。
    • 是的,你是对的,这个问题出现在 android 6 或更高版本中。为此,您需要在运行时询问用户的许可。这可以使用 Android Permissions 插件来解决。在低于 6 的 android 版本上尝试此代码,您的文件将成功保存。
    【解决方案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】:

      我知道这已经晚了,但我一直遇到 FileTransfer 插件的问题。也许这只是我。相反,我使用 File 插件的 writeFile() 方法取得了成功。

      我仍在使用 iOS,但对于 Android,这就是我所拥有的:

      import { File } from "@ionic-native/file";
      
      constructor(private fileSystem: File) {}
      

      那么,无论你有什么逻辑来保存文件,我们都有:

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

      正如我所说,我仍在寻找适用于 iOS 的路径。而且我仍然想知道如何弹出通常在下载实际进入下载文件夹时出现的通知。但至少我可以直接保存在安卓的下载文件夹中。

      【讨论】:

        【解决方案5】:

        来自 josh morony 的这段代码 - ionic 3 电容器 - 从 tmp 目录中拍摄一张照片,并使用 FileSystem API 将其写入本节中的 Document 目录,然后检索和操作路径

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

        }

        在 ionic 3 中,您必须使用 cordova File 插件 - 请 google。这很容易理解:您在该函数中定义文件所在的原始目录、文件的原始名称、目标目录以及文件的新名称。原理是一样的。

        【讨论】:

          【解决方案6】:

          要将文件下载到下载目录,您需要使用 Cordova 文件插件:

          import { File } from '@ionic-native/file/ngx';
          
          constructor(
              private file: File,
            ) { }
          
          this.file.writeFile(this.file.externalRootDirectory + '/Download/', user_log.xlsx, blob, { replace: true })
          .then(() => {
          
                        alert('File has been downloaded. Please check your downloads folder.')
              enter code here
                      }, 
              (err) => {
          
                        alert("Sorry. An error occurred downloading the file: " + err);
              enter code here
                      });
                    })
          

          它也适用于 Ionic 4。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-08-28
            相关资源
            最近更新 更多