androidnativescriptnativescript-angularnativescript-plugin

How to correct read file from "Downloads" folder in NativeScript app?


I write a Android app on NativeScript.

I have defined required permissions in App_Resources/Android/AndroidManifest.xml:

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

I know that it's not enough for getting access to storage, so I have requested permission in runtime and check it in System settings.

After downloading some image by browser to Downloads folder I wanna read it in my app. Initially I got a file path by nativescript-mediafilepicker, but for know I use following snippet:

console.log(fs.File.exists('/storage/emulated/0/Download/7zoVG9uML7AyjwHl.png'));
const file = fs.File.fromPath('/storage/emulated/0/Download/7zoVG9uML7AyjwHl.png');
file.readSync(e => console.log('ERROR ' + e));

which print in console:

JS: true
JS: ERROR Error: java.io.FileNotFoundException: /storage/emulated/0/Download/7zoVG9uML7AyjwHl.png: open failed: EACCES (Permission denied)

What I do wrong?

UPDATE I added WRITE_EXTERNAL_STORAGE permission, but it has no effect:

permissions.requestPermissions(p).then(async () => {
  const publicDirectory = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
  const fullPath = `${publicDirectory}/7zoVG9uML7AyjwHl.png`;
  const file = fs.File.fromPath(fullPath);
  file.readSync(e => console.log('ERROR ' + e));
});
JS: ERROR Error: java.io.FileNotFoundException: /storage/emulated/0/Download/7zoVG9uML7AyjwHl.png: open failed: EACCES (Permission denied)

Solution

  • So, the solution is:

    1. Add in AndroidManifest.xml
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    1. Add in AndroidManifest.xml
    <application android:requestLegacyExternalStorage="true" ...>
    
    
    1. Get file by string path:
    const file = fs.File.fromPath('/storage/emulated/0/Download/7zoVG9uML7AyjwHl.png');
    file.readSync(e => console.log('ERROR ' + e));