cordova-plugin-file: Cordova can't read files with FileRead

I’m using JavaScript’s FileReader API to try to get the blob of a file inside a Cordova application.

My code is like the example below:

originalLocation = 'content://com.android.externalstorage.documents/document/primary%3ADownload%2F1671641692909.jpg';

window.FilePath.resolveNativePath(originalLocation, function (newFilepath) { resolveFilePath(newFilepath) });

function resolveFilePath(location) {
    window.resolveLocalFileSystemURL(location, function (fileEntry) {

        fileEntry.file(function (file) {

            let reader = new FileReader();

            reader.onload = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onloadstart = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onloadend = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onprogress = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onerror = function (event) {
                console.log(reader.result);
                console.log(event);
                const error = reader.error;
                console.log(error);
            }
            reader.onabort = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            console.log(file);
            reader.readAsArrayBuffer(file);
        });
    });
}
<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
       <application requestLegacyExternalStorage="true" />
</edit-config>

<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />

When reading an image, the API works correctly, obtaining the content, but with files that are not images, the FileReader’s onerror event always returns the message “FileError {code: 1}”. I already tried to read using all possible ways (readAsArrayBuffer, readAsBinaryString, readAsDataURL,readAsText).

The location of files on the smartphone.

  • Image before resolveLocalFileSystemURL: content://com.android.externalstorage.documents/document/primary%3ADownload%2F1671641692909.jpg
  • Image after resolveLocalFileSystemURL: file:///storage/emulated/0/Download/1671641692909.jpg - Success
  • File before resolveLocalFileSystemURL: content://com.android.externalstorage.documents/document/primary%3ADownload%2FExample.pptx
  • File after resolveLocalFileSystemURL: file:///storage/emulated/0/Download/Example.pptx - Error

What could possibly be happening?

Environment, Platform, Device

Android 12 - Samsung A 53

Version information

Cordova: 11.1.0 Cordova-Android: 10.1.2

Checklist

  • I searched for existing GitHub issues
  • I updated all Cordova tooling to most recent version
  • I included all the necessary information above

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

The files I’m trying to open are on the device itself and not on external storage.

Android has 2 storage mediums, internal and external storage. Both can be on the device. External storage are generally attached to an SD card (will have a /sdcard/... path, however most devices will also emulate external storage if the sdcard is not present, or not supported (generally uses a /storage/emulated/0/... path).

So a filepath like file:///storage/emulated/0/Download/1671641692909.jpg tells me that you’re working with external storage, and thus Scoped Storage rules applies.

Documents have stricter rules than media files, so if the app has READ_EXTERNAL_STORAGE permission granted (and this plugin will request it when appropriate), you may read media off the external storage (subject to permissions set my the app who wrote that media file). However, I don’t READ_EXTERNAL_STORAGE applies to document files, such as those that are generally found in Downloads/ or otherwise. I believe the only way to read document files is via the native MediaStore APIs which the file plugin does not implement (they aren’t really friendly to file-like API cause they don’t really share the same concepts). This is also kinda further enforced that in API 33 and later READ_EXTERNAL_STORAGE becomes obsolete in favour of 3 new permissions, READ_MEDIA_IMAGES, READ_MEDIA_AUDIO, READ_MEDIA_VIDEO, however there is no explicit READ` permission for documents.

This is why I suggested something like https://www.npmjs.com/package/cordova-plugin-saf-mediastore which contains APIs like readFile(uri:string):Promise<ArrayBuffer>, so the plugin not only provides the way to choose files via MediaStore & the file picker, but to also read and get the contents of the files, or write/overwrite… whereas https://www.npmjs.com/package/cordova-plugin-filechooser looks like only allows you to select files and returns a content URL, which thie cordova-plugin-file can only use if it leads to a file that is readable using filesystem APIs.

@etcho, pt-BR: Eu vou postar todo o meu código desde a parte que o app dispara a escolha de arquivos. Dependendo do local ou gerenciador de arquivos usados no Android, ele pode apresentar problema. É uma confusão.

en-US: I’m going to post all my code from the part where the app triggers the choice of files. Depending on the location or file manager used on Android, it may have problems. It’s a mess.

fileChooser.open($scope.selectFileAndUpload, error);

$scope.selectFileAndUpload = function (data) {
    var location;

    if (data.url === undefined) {
        location = data;
    } else {
        location = data.url;
    }

    if (location.indexOf('content://') === 0) {

        window.FilePath.resolveNativePath(location, function (newFilepath) {
            resolveFilePath(newFilepath);
        }, function (error) {
            if (error.code === 0) {
                console.log('Não foi possível ler este arquivo.')
            } else if (error.code === 1) {
                console.log('Problema no Google Drive.',) 
            }
        });
    } else {
        resolveFilePath(location);
    }

}

function resolveFilePath(location) {
    window.resolveLocalFileSystemURL(location, function (fileEntry) {

        fileEntry.file(function (file) {

            let fileType = file.type;

            let reader = new FileReader();

            reader.onloadend = function (e) {
                let imgBlob = new Blob([this.result], { fileType });

                $scope.filesToUpload.forEach(element => {
                    if (element.url === location) {
                        element.blob = imgBlob;
                    }
                });

            }

        }, function () {
            console.log('Ocorreu um erro ao ler o arquivo.');
        });
    }, function (e) {
        console.log('Ocorreu um erro ao ler o arquivo.');
    });
}