Filesystem: Not able to create 'DOCUMENTS' on Android 10

I have a base64 of a PDF that I want to open and I’m using:

import {FileOpener} from "@ionic-native/file-opener/ngx";
import {FilesystemDirectory, Plugins} from '@capacitor/core';
const {Filesystem} = Plugins;

The method is:

openPdfFromBase64(base64: string) {
    // Save the PDF to the device
    const fileName = `MyAwesomeFile.pdf`;
    try {
      Filesystem.writeFile({
        path: fileName,
        data: base64,
        directory: FilesystemDirectory.Documents
        // encoding: FilesystemEncoding.UTF8
      }).then((writeFileResult) => {
        Filesystem.getUri({
          directory: FilesystemDirectory.Documents,
          path: fileName
        }).then((getUriResult) => {
          const path = getUriResult.uri;
          this.fileOpener.open(path, 'application/pdf')
            .then(() => {
              // console.log('File is opened');
            })
            .catch(error => {
              console.log('Error opening file', error);
            });
        }, (error) => {
          console.log(error);
        });
      });
    } catch (error) {
      console.error('Unable to write file', error);
    }
  }

On iOS it’s working good, but in Android (API 29, Android 10.0) it’s not working. The app asked me for permissions but then, the file was not opened.

The logs in Android Studio says:

V/Capacitor/Filesystem: Permission 'android.permission.WRITE_EXTERNAL_STORAGE' is granted
E/Capacitor/Filesystem: Not able to create 'DOCUMENTS'!
D/Capacitor: Sending plugin error: {"save":false,"callbackId":"35117243","pluginId":"Filesystem","methodName":"writeFile","success":false,"error":{"message":"NOT_CREATED_DIR"}}

Capacitor versions:

Installed Dependencies:

  @capacitor/cli 2.4.0
  @capacitor/ios 2.4.0
  @capacitor/android 2.4.0
  @capacitor/core 2.4.0
  @capacitor/electron not installed

[success] Android looking great! 👌
  Found 1 Capacitor plugin for ios:
    cordova-plugin-file-opener2 (3.0.3)

Any idea how can I fix this?

From the documentation:

The Documents directory. […] It’s not accesible on Android 10 unless the app enables legacy External Storage by adding android:requestLegacyExternalStorage="true" in the application tag in the AndroidManifest.xml

7 Likes

you saved my life, love you

thank you so much, bro :slight_smile: