How to save a file on shared space in Cordova with Android?

2.2k Views Asked by At

I am using Apache Cordova with cordova-plugin-file to develop some android app. Since Android API 29 (Android 10), apps no longer have access to shared space directly due to privacy issues.

I was storing some pdf file on file:///storage/emulated/0/Download/ from where the user could then open the pdf file.

window.resolveLocalFileSystemURL('file:///storage/emulated/0/Download/', function (dir) {
  dir.getFile(filename, { create: true }, function (file) {
    file.createWriter(function (fileWriter) {
      console.log('Writing content to file')

      fileWriter.onwriteend = function () {
        console.log('Successful file write...')
      }

      fileWriter.onerror = onerror

      fileWriter.write(DataBlob)
    }, onerror)
  }, onerror)
}, onerror)

But that stopped working on Android 10.

How can I store now a file to be accessible by the user?

1

There are 1 best solutions below

0
João Pimentel Ferreira On

window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory + "/Download" used to work

  • This should work as is when targeting API 28 (now forbidden by Google Play)
  • This should work when targeting API 29 with the dev version of the plugin (which has the android:requestLegacyExternalStorage="true"), alternatively you can use the edit-config to add this flag.
  • This won't work when targeting API 30, as API 30 ignores the android:requestLegacyExternalStorage attribute.

It's important to read the Android Notes before you target API 30. You may need to migrate your files to another folder to maintain access to them when targeting API 30 using the new APIs. Source.

Solution for up to Android 10 (API 29)

Use the dev version of the plugin

cordova plugin rm cordova-plugin-file
cordova plugin add https://github.com/apache/cordova-plugin-file.git

I tested it and it allows me to use cordova.file.externalRootDirectory + "/Download" in Android 10 (API 29)