简体   繁体   中英

How to read text file from sdCard on ionic2 and android 5?

I am trying to open a text file and put the content in sqlite db. The issue is that I cant read the file in any way. Below is closest to success I managed to accomplish. When executed it produces FileError(2): "SECURITY_ERR".

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

On phone I see that the app has rw access on sd card and in platform/AndroidManifest.xml i have set:

  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I've spent lot of time digging through the internet and trying different solutions with no success.

Edit:

Here is what console.log(cordova.file); outputs:

applicationDirectory: "file:///android_asset/"
applicationStorageDirectory: "file:///data/data/com.ionicframework.leki645195/"
cacheDirectory: "file:///data/data/com.ionicframework.leki645195/cache/"
dataDirectory: "file:///data/data/com.ionicframework.leki645195/files/"
documentsDirectory: null
externalApplicationStorageDirectory: "file:///storage/emulated/0/Android/data/com.ionicframework.leki645195/"
externalCacheDirectory: "file:///storage/emulated/0/Android/data/com.ionicframework.leki645195/cache/"
externalDataDirectory: "file:///storage/emulated/0/Android/data/com.ionicframework.leki645195/files/"
externalRootDirectory: "file:///storage/emulated/0/"
sharedDirectory: null
syncedDataDirectory: null
tempDirectory: null

Try this code,

openFile() {
  this.fileChooser.open()
  .then(uri => {

    this.file.resolveLocalFilesystemUrl(uri)
    .then(entry=>{

      let path = entry.nativeURL;

      //read file contents
      var rawFile = new XMLHttpRequest();
      rawFile.open("GET", path, false);
      rawFile.onreadystatechange = function ()
      {
          if(rawFile.readyState === 4)
          {
              if(rawFile.status === 200 || rawFile.status == 0)
              {
                var fileText = rawFile.responseText;
                alert(fileText); 
              }
          }
      }
      rawFile.send(null);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM