【问题标题】:Download CSV file from assets folder in IONIC 3从 IONIC 3 中的资产文件夹下载 CSV 文件
【发布时间】:2019-02-24 08:24:27
【问题描述】:

我有一个demo-file.csv 文件,它在assets/csv 文件夹中,所以我如何从手机下载它,

这是我的 HTML 和组件代码。

HTML 代码

<button ion-button type="button" block (click)="downloadFile('assets/csv/demo-file.csv', 'demo-file.csv')">Download Demo File</button>

组件代码

 public downloadFile(link: any, fileName: any) {
      if (link) {
        let path = null;
        this.showWaitingLoading();
        if (this.platform.is('ios')) {
          path = this.file.documentsDirectory;
        } else {
          path = this.file.dataDirectory;
      }

      const transfer = this.transfer.create();

      transfer.download(link, path + fileName).then(entry => {
        this.dismissWaitingLoading();
        this.openFile(entry.toURL());
      }).catch(() => {
        this.dismissWaitingLoading();
        this.showToastMsg('error', "Something went wrong");
      });
     }
    }
/* ================= OPNE FILE FUNCTION ===========*/

public openFile(path: any) {
   this.fileOpener.open(path, 'application/*')
     .then(() => console.log('File is opened'))
     .catch((e: any) => console.log('Error openening file', e));
}

我无法下载文件,我的 PATH 中是否缺少任何东西?

【问题讨论】:

  • 你不需要前导斜线吗? /assets/csv/demo-file.csv?下载失败时会出现什么错误?
  • @David 我也尝试使用斜线,但没有成功。
  • 那么你得到了什么错误?

标签: javascript angular ionic2 ionic3 file-transfer


【解决方案1】:

尝试使用Http get读取并写成Blob,示例代码如下,

export class csvPage {
  csvData: any[] = [];
  headerRow: any[] = [];

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    private http: Http) {
      this.readCsvData();
  }

  private readCsvData() {
    this.http.get('assets/dummyData.csv')
      .subscribe(
      data => this.extractData(data),
      err => this.handleError(err)
      );
  }

  private extractData(res) {
    let csvData = res['_body'] || '';
    let parsedData = papa.parse(csvData).data;

    this.headerRow = parsedData[0];

    parsedData.splice(0, 1);
    this.csvData = parsedData;
  }

  downloadCSV() {
    let csv = papa.unparse({
      fields: this.headerRow,
      data: this.csvData
    });

    // Dummy implementation for Desktop download purpose
    var blob = new Blob([csv]);
    var a = window.document.createElement("a");
    a.href = window.URL.createObjectURL(blob);
    a.download = "newdata.csv";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  private handleError(err) {
    console.log('something went wrong: ', err);
  }

}

【讨论】:

    【解决方案2】:

    您可以使用库...此外,HttpClient 可以为您读取数据为Blob

    npm i file-saver

    // my.component.ts
    
    import * as fileSaver from 'file-saver';
    
    export class MyComponent {
    
      constructor(private http: HttpClient){}
    
      downloadFile(path: string) {
        this.startLoading();
        this.http.get(`${MY_APP_URL}/${path}`, { responseType: 'blob' })
          .pipe(tap(blob: Blob => fileSaver.saveAs(blob, 'your_csv_file_name.csv')))
          .subscribe(() => this.stopLoading(), err => this.handleErr(err));
      }
    }
    

    希望这会有所帮助:-)

    【讨论】:

    • @Heerhaaw 我的文件位于 /src/assets/csv/demo-file.csv ,所以我可以在 ${MY_APP_URL}/${path} 中输入什么路径b>,那是我不知道
    • 试试this.http.get('/assets/csv/demo-file.csv', ...)
    【解决方案3】:

    HTML 代码

     <button ion-button type="button" block (click)="downloadFile('demo-file.csv')">Download Demo File</button>
    

    组件代码

     declare var cordova: any; // declare Top Section of component
     public downloadFile(link: any) {
      if (link) {
        let path = null;
        this.showWaitingLoading();
        if (this.platform.is('ios')) {
        path = cordova.file.documentsDirectory;
      } else {
        path = cordova.file.dataDirectory;
      }
    
      const transfer = this.transfer.create();
      const imageLocation = `${cordova.file.applicationDirectory}www/assets/csv/${link}`;
    
      transfer.download(imageLocation, path + link).then(entry => {
        this.dismissWaitingLoading();
        this.openFile(entry.toURL());
      }).catch(() => {
        this.dismissWaitingLoading();
        this.showToastMsg('error', "Something went wrong");
      })
     }
    
     /* ================= OPNE FILE FUNCTION ===========*/
     public openFile(path: any) {
      this.fileOpener.open(path, 'application/*')
       .then(() => console.log('File is opened'))
       .catch((e: any) => console.log('Error openening file', e));
     }
    

    请试试这个

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 1970-01-01
      • 2022-01-21
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多