javascript - Download CSV file from assets folder in IONIC 3 - Stack Overflow

I have one demo-file.csv file and it is in the assetscsv folder, so how can I download it from mobile,

I have one demo-file.csv file and it is in the assets/csv folder, so how can I download it from mobile,

here is my HTML & COMPONENT code.

HTML CODE

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

COMPONENT CODE

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

I'm not able to download the file, is there any thing missing in my PATH?

I have one demo-file.csv file and it is in the assets/csv folder, so how can I download it from mobile,

here is my HTML & COMPONENT code.

HTML CODE

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

COMPONENT CODE

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

I'm not able to download the file, is there any thing missing in my PATH?

Share Improve this question edited Sep 20, 2018 at 6:35 core114 5,34517 gold badges109 silver badges199 bronze badges asked Sep 20, 2018 at 5:20 Apurv ChaudharyApurv Chaudhary 1,7953 gold badges34 silver badges58 bronze badges 3
  • Don't you need a leading slash? /assets/csv/demo-file.csv? And what error do you get when the download fails? – David Commented Sep 24, 2018 at 13:13
  • @David i tried also with slash but it didn't work. – Apurv Chaudhary Commented Sep 24, 2018 at 14:06
  • So what error do you get? – David Commented Sep 24, 2018 at 14:24
Add a ment  | 

3 Answers 3

Reset to default 2

Try to read it using Http get and write it as a Blob, Sample code as follows,

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

}

Html Code

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

Component Code

 declare var cordova: any; // declare Top Section of ponent
 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));
 }

Please try this one

You can use a library... Also, the HttpClient can read data as Blob for you.

npm i file-saver

// my.ponent.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));
  }
}

Hope this helps a little :-)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745345010a4623503.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信