19

Trying to figure out how to create a directory on the file system using PhoneGap.

I want to create a directory for my PhoneGap application, so I can store images the user creates there and load them back up in the app.

2 Answers 2

40

This is how you do it :

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null); 

function onRequestFileSystemSuccess(fileSystem) { 
        var entry=fileSystem.root; 
        entry.getDirectory("example", {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail); 
} 

function onGetDirectorySuccess(dir) { 
      console.log("Created dir "+dir.name); 
} 

function onGetDirectoryFail(error) { 
     console.log("Error creating directory "+error.code); 
} 

On iOS, this script will create a directory named 'example' in Applications/YOUR_APP/Documents/

4
  • 3
    yep, that works. I was just about to answer my question since I found that as well. Funny how I can't find an answer until I post it on SO, then I find it immediately. Feb 18, 2012 at 17:14
  • @JohnSonmez Which code do you use to save the image?
    – Michael
    Apr 7, 2014 at 15:29
  • @titouan-de-baileul does it require some extenal sources
    – Meer
    May 10, 2016 at 7:01
  • Doesn't seem to be working for me. I added <preference name="AndroidPersistentFileLocation" value="Compatibility" />, <gap:plugin name="org.apache.cordova.file"/> and <gap:plugin name="org.apache.cordova.file-transfer"/> to my config.xml but still it's not working :( Aug 28, 2016 at 0:56
-1

This code works for me (based on version 7 Cordova documentation - https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html):

window.resolveLocalFileSystemURL('cdvfile://localhost/persistent/',
  function fileEntryCallback(fileEntry) {
    fileEntry.getDirectory('my_directory', { create: true });
  }
);

If the code above doesn't work, you may need to reinstall the File and File Transfer plugins. A command like console.log(window.resolveLocalFileSystemUrl) is one way to test that the plugins are working.

Also, if you're using Content Security Policy (CSP) be sure your default-src allows cdvfile: paths:

default-src cdvfile:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.