如何从ionic2和android 5上的sdCard读取文本文件?

时间:2017-03-07 20:17:20

标签: android cordova ionic-framework ionic2

我正在尝试打开一个文本文件并将内容放在sqlite db中。问题是我无法以任何方式阅读该文件。以下是我设法完成的最接近的成功。执行时会产生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));
    });
  }

在手机上,我看到应用程序在SD卡上有rw访问权限,并且platform/AndroidManifest.xml已设置:

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

我花了很多时间在互联网上挖掘并尝试不同的解决方案但没有成功。

编辑:

以下是console.log(cordova.file);输出的内容:

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

1 个答案:

答案 0 :(得分:0)

试试这段代码,

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