Peter
Peter

Reputation: 328

How to read a text file that was downloaded locally (Ionic 2 and Cordova)

I've downloaded a file from my webserver using the following code:

download = () : void => {
  this.platform.ready().then(() => {
  let pathToSaveTo = "";

  let filename = this.url.substring(this.url.lastIndexOf('/') + 1);

  if (this.platform.is('android')) {
      pathToSaveTo = cordova.file.dataDirectory + filename;
  }
  else if(this.platform.is('ios')) {
      pathToSaveTo = cordova.file.dataDirectory + filename;
  }

  let ft = new Transfer();

  ft.download(this.url, pathToSaveTo).then(() => {
      this.savedTo = pathToSaveTo;
  });
})

I'm having a lot of trouble finding out a way to open the .txt file and read the text inside. I've looked for quite a while, and it seems like using Ionic native would be the best, but how exactly would I go about that? If someone could provide an example I would really appreciate it.

If anybody has any specific questions about what I'm trying to achieve I'll make edits.

Thanks!

Upvotes: 0

Views: 1908

Answers (1)

Kinorsi
Kinorsi

Reputation: 553

I use FileChooser open and read a file. Maybe this can give you some idea.

openFile(): void {
  FileChooser.open()
  .then(uri => {
    File.resolveLocalFilesystemUrl(uri)
    .then(entry=>{
      let path = entry.nativeURL.substring(0, entry.nativeURL.lastIndexOf('/'));
      File.readAsText(path, entry.name)
      .then(content=>{
        console.log(content);
      })
      .catch(err=>{
        console.log(err);
      });
    })

  })
  .catch(e => console.log(e));
}

Upvotes: 1

Related Questions