Reputation: 15558
In my Ionic2 app I managed to successfully use certain methods of the File plugin such as:
Now I want to use readAsText (as specified in the docs) but I can't figure out how to get a fileEntry without creating a new file, (which apparently would require overriding it)?
Upvotes: 4
Views: 2876
Reputation: 165
You can get a fileEntry by using cordova-plugin-filepath
If you have an URI starting with "content://", we need the local file URI starting with "file://".
FilePath.resolveNativePath returns the local file url.
let uri = "content://com.android.externalstorage.documents/document/primary/data...";
window.FilePath.resolveNativePath(uri, (localFileUri) => {
// result is file:///storage/emulated/0/Android/data/...
// now get a fileEntry from this uri
window.resolveLocalFileSystemURL(localFileUri, (fileEntry) => {
});
});
File Entry, has a method "file" which can be used to get a file object and read the content of the file with FileReader, e.g:
fileEntry.file((file) => {
var reader = new FileReader();
reader.onloadend = (e) => {
let result = e.target.result; // text content of the file
// do whatever you like
};
reader.readAsText(file);
Upvotes: 2
Reputation: 399
Here is an example of using the readAsText()
function if you know the path of the file:
const fs:string = cordova.file.externalRootDirectory;
File.readAsText(fs, filePath).then((contents) => {
if(typeof contents == 'string'){
processFile(contents);
}
});
One slight gotcha is that the file path must not start with a /
.
An example where this might catch you is when processing files in a directory;
const fs:string = cordova.file.externalRootDirectory;
File.listDir(fs, "").then(files => {
for (let file of files){
if(file.name.toLowerCase().endsWith(".csv")){
File.readAsText(fs, file.fullPath.substr(1)).then((contents) => {
if(typeof contents == 'string'){
processFile(contents);
}
});
}
}
});
Upvotes: 1