I am making a Cordova application from which I need to export a file. I would like to save the file to the Android device's storage: /storage/emulated/0/
. The app should create a folder in which it will create a file with content in it.
I tried the cordova-plugin-file
plugin but I'm not sure how to use it. There are examples on the plugin's documentation but I don't know which one to use, there is:
And I tried them all however none of them works.
Your help and an example (if possible) would be greatly appreciated.
EDIT
There's the code I used. I'm not getting any error.
function createFile(dirEntry, fileName, fileContent, isAppend) {
dirEntry.getFile(fileName, {create: true, exclusive: false}, function(fileEntry) {
writeFile(fileEntry, fileContent, isAppend);
}, fail);
}
function savePasswords(fileSystem) {
createFile("/sdcard/testFolder", "testfile.txt", "TEST", true);
}
function fail(error) {
alert("ERROR: " + error.code);
}
function request() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, savePasswords, fail);
}
document.addEventListener("deviceready", request, false);
I want this to create the file "testfile.txt" with content "TEST" in a folder named "testFolder".
Since Android 4.4, the SD card root (
/sdcard/
) is read-only so you cannot write to it. Assuming your reference towriteFile()
in your example code refers to the cordova-plugin-file example (since it's not defined in your code), then thefileWriter.onerror()
function would be invoked with error codeNO_MODIFICATION_ALLOWED_ERR
.You must write to the application storage directory on the SD card (e.g.
/sdcard/Android/data/your.app.package.id/
). You can reference this location usingcordova-plugin-file
ascordova.file.externalApplicationStorageDirectory
.See this answer for details of SD card access in different versions of Android.
Note: above references to "SD card" refer to the emulated SD card (on internal memory (i.e.
/storage/emulated/0/
). Referencing the external/removable SD card present in some Android devices (e.g. Samsung Galaxy S range) is not possible viacordova-plugin-file
, however you can use getExternalSdCardDetails() from cordova-diagnostic-plugin to do so.This script works: