File storage in custom directory?

Using the Capacitor Filesystem API, can I save files in any directory on my device ?
Something like:

Filesystem.writeFile({
        data: 'testcontent', 
        path: 'file://storage/emulated/0/anydir/testfile.txt',
        encoding: Encoding.UTF8,
        recursive: true
)}

I was only able to save files in file:///storage/emulated/0/Android/data/io.ionic.starter/files using the following code:

Filesystem.writeFile({
        data: 'testcontent',
        directory: Directory.External,
        path: 'anydir/testfile.txt',
        encoding: Encoding.UTF8,
        recursive: true
)}

with the file being saved in file:///storage/emulated/0/Android/data/io.ionic.starter/files/anydir/testfile.txt

No. It would be anarchy if a given application could stomp all over the files from other applications. The details of what directories are accessible how is OS-specific.

But with the right Capacitor plugin (Java code) it should be possible, right ? I mean in most apps that create data, you can select the specific directory in which you want to save the files.

Not 100% true. Apps these days create their own sandbox storage systems. So when you save something to the “documents” it’s typically a special directory that is isolated to inside the sandbox of that app.

Unlimited access to the file-system is …while not going to fly, especially in todays world of tighter security and needing permissions for things.

1 Like

Filesystem plugin allows to use absolute file urls, or relative if you pass the directory.

If you don’t pass the directory and use the absolute file url it might work depending on the path, it’s possible to read/write on the paths that “belong” to your app, and some other public “shared” folders.

But those public “shared” folders are no longer available on Android 10 unless you enable the legacy filesystem, and no longer available on Android 11+ even if you enabled the legacy filesystem.

On Android 11+, might be possible to write everywhere if you add (and request) the MANAGE_EXTERNAL_STORAGE permission, which Filesystem plugin doesn’t request.

All the above is just for Android, on iOS there are no public shared folder you can write to, you can only read/write inside your app sandbox. I think in Capacitor 2 the file urls won’t work on iOS, but they will in Capacitor 3 with @capacitor/filesystem plugin.

Your code is probably not working because you have used file://, while the path should start with file:///

2 Likes