I'm trying to read the content of a file located in /storage/emulated/0/... using cordova-plugin-file. I'm able to get the related FileEntry and read some properties like name, type or size but when I use a FileReader to read the content it fails with FileError {code: 1}
FileError - API states that error code 1 is NOT_FOUND_ERR but I'm sure the file exists. As I said, I'm able to retrieve it's size (I've checked that the value is correct!).
I use the following code to test:
window.resolveLocalFileSystemURL(
"cdvfile://localhost/sdcard/ticket/fake.pdf",
function(fileEntry) {
console.log("ENTRY URL " + fileEntry.toURL());
console.log("IS FILE: " + fileEntry.isFile);
fileEntry.file(function(file){
console.log("FILE: " + file.name);
console.log("SIZE: " + file.size);
console.log("TYPE: " + file.type);
var reader = new FileReader();
reader.onloadend = function() {
console.log("READER END");
console.log(this.result);
};
reader.onerror = function(er) {
console.log("READER ERROR");
console.log(er);
};
reader.readAsDataURL(file);
}, console.error);
},
console.error
);
the output is:
ENTRY URL file:///storage/emulated/0/ticket/fake.pdf
IS FILE: true
FILE: fake.pdf
SIZE: 32471
TYPE: application/pdf
READER ERROR
ProgressEvent {type: "error", bubbles: false, cancelBubble: false, cancelable: false, lengthComputable: false, …}
READER END
where: ProgressEvent.target is FileReader and ProgressEvent.target._error is FileError {code: 1}
I've also tried with other paths or files:
file:///storage/emulated/0/ticket/fake.pdffile:///storage/emulated/0/DCIM/Camera/IMG_20190412_110205.jpg
AndroidManifest.xml has:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
The answers to other similar questions that I have found propose as a solution what I am already doing.
UPDATE:
It seems to be a permissions problem. If I do
window.resolveLocalFileSystemURL("cdvfile://localhost/sdcard/ticket/fake.pdf", okFunction, errorHandler);
it doesn't triggers the permission request to the user. But it does with:
window.resolveLocalFileSystemURL("cdvfile://localhost/sdcard/ticket/fake.pdf", function(f) {
f.filesystem.root.getFile(f.fullPath, {}, okFunction, errorHandler)
}, errorHandler);
Once the user accepts the permission, all methods works fine.
Now my question is why if I use the FileEntry from window.resolveLocalFileSystemURL to read the content it doesn't request the permission but it does for the FileEntry from filesystem.root.getFile.