Search code examples
androidcordovaphonegap-pluginsphonegap-build

Phonegap - How to save .txt file in root directory of android mobile


I m trying to save a .txt file in root directory of android mobile using phonegap. I have installed these plugins 'cordova-plugin-file' and 'cordova-plugin-file-transfer'. In config.xml file i add this preference.

<preference name="AndroidPersistentFileLocation" value="Internal" />

Here is my code.

<button class="btn-lg btn-success" onclick="saveFile('hello_world.txt', 'This is Dummy Content')">Write File</button>

Code to handle on click event.

function saveFile(fileName, fileData) {
    // Get access to the file system
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
        // Create the file.
        fileSystem.root.getFile(fileName, {create: true, exclusive: false}, function (entry) {
            // After you save the file, you can access it with this URL
            var myFileUrl = entry.toURL()
            entry.createWriter(function (writer) {
                writer.onwriteend = function (evt) {
                    alert("Successfully saved file to " + myFileUrl)
                }
                // Write to the file
                writer.write(fileData)
            }, function (error) {
                alert("Error: Could not create file writer, " + error.code)
            })
        }, function (error) {
            alert("Error: Could not create file, " + error.code)
        })
    }, function (evt) {
        alert("Error: Could not access file system, " + evt.target.error.code)
    })
}

After success callback it return this file location.

file:///data/data/com.adobe.phonegap.app/files/files/hello_world.txt

But when i try to find this file in given location. Its not there. I want this file in my root directory of mobile.


Solution

  • Check out this link that contains the working sample.

    The link contains sample cordova app for file download, save and open. Supports folder deletion option as well.

    Check out the readme section. Hope it helps. Also you can check out this SO Post for more info on this.