下载.csv文件与角度2 - 离子2

时间:2017-05-02 11:14:43

标签: angular typescript ionic2

我有一个Ionic 2应用程序,我需要从服务器下载sample.csv文件。我已经有了我需要做的请求的网址:

 let url = 'http://example.com/download/sample.csv';

我想知道如何做到这一点。我尝试使用ionic2 FileTransfer:

 importleads(){
     const fileTransfer: TransferObject = this.transfer.create();
     let url = 'http://example.com/download/sample.csv';
     fileTransfer.download(url, this.file.dataDirectory + 'Import_Leads_Sample.csv').then((entry) => {
        if(entry) {
           console.log('download complete: ' + entry.toURL());
           let alert = this.alertCtrl.create({
           title: 'Lead Downloaded Successfully',
           buttons: [{
                     text: 'Ok',
                    }]
           });
           alert.present();
        }
        else{
            let alert = this.alertCtrl.create({
            title: 'No File to download',
            buttons: [{
                       text: 'Ok',
                     }] 
            });
            alert.present();
        }
     });
}

<button ion-button (click)="importleads()">Test File Download</button>

我已生成android-debug.apk文件并将其安装在三星手机中。我收到警告消息Lead Downloaded Successfully但没有文件下载到设备中。我搜索了整个手机磁盘但没找到文件。

如果我将此网址放入浏览器,则会开始下载,但不会使用FileTransfer。

1 个答案:

答案 0 :(得分:0)

不使用this.file.dataDirectory + file_name.csv作为文件路径,而是将代码修改为:

首先在构造函数中添加它:

确保您正在使用您正在使用正确的文件路径,假设您也可以在ios上使用它

  storageDirectory: string = '';
  // make sure this is on a device, not an emulation (e.g. chrome tools device mode)
  if(!this.platform.is('cordova')) {
    return false;
  }

  if (this.platform.is('ios')) {
    this.storageDirectory = cordova.file.documentsDirectory;
  }
  else if(this.platform.is('android')) {
    this.storageDirectory = cordova.file.dataDirectory;
  }
  else {
    // exit otherwise, but you could add further types here e.g. Windows
    return false;
  }

现在你的代码:

importleads()
{
    const fileTransfer: TransferObject = this.transfer.create();
    let url = 'http://example.com/download/sample.csv';
    fileTransfer.download(url, this.storageDirectory  + 'Import_Leads_Sample.csv').then((entry) => {
        if (entry) {
            console.log('download complete: ' + entry.toURL());
            let alert = this.alertCtrl.create({
                title: 'Lead Downloaded Successfully',
                buttons: [{
                    text: 'Ok',
                }]
            });
            alert.present();
        }
        else {
            let alert = this.alertCtrl.create({
                title: 'No File to download',
                buttons: [{
                    text: 'Ok',
                }]
            });
            alert.present();
        }
    });
}

请注意我在文件路径中进行更改的区别。 此代码段取自dsgriffin ionic file tranfer repo

中的file