Open Source / XRap

Having a Dialog with the nsIFilePicker

Probably once of the most simple but useful interfaces that I have come across is the nsIFilePicker. This interface will allow the end-user to use a dialog for loading or saving a file, or getting folder for use in your application. In my case I just need the user to get the path to a directory.

function openDirDialog()
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes[“;1”]

fp.init(window,”Select Directory”,nsIFilePicker.modeGetFolder);
var ret =;
if (ret == nsIFilePicker.returnOK || ret == nsIFilePicker.returnReplace) 
applicationPath = fp.file.path;
document.getElementById(‘tb_inputPath’).value = applicationPath;

  • nsIFilePicker – The declaration of this const is not needed, but it does make some operations easier as you will see
  • fp – Gets the nsIFilePicker interface component, so that you can actually call the File Picker
    • fp.init(nsIDOMWindow, title, mode) – This is where you set the inital settings for the file picker, this needs to be called if you want it to work.  
      • nsIDOMWindow – parameter sets the who will be the parent of the dialog, in my case it is just the main window, so I used ‘window’.  
      • title – Is simply a string, where you would set the Title of the dialog
      • mode – This is where you declare what you want the dialog to actually do, whether it be loading or saving a file, or getting a folder. Here is a table of the different mode options:
        modeOpen 0
        modeSave 1
        modeGetFolder 2
        modeOpenMultiple 3
    • – This call actually shows the File Picker dialog according to the mode you have chosen.  The return types are as follows:
      returnOK 0
      returnCancel 1
      returnReplace 2
    • As you can see, by using the nsIFilePicker const at the beginning, I can use its attributes to check the return value from the dialog.
    • There are filters you can append to the File Picker to direct the user to only a specific type of file, by using the .appendFilters(filter).  Here is a set of predifined filters:
      filterAll 1
      filterHTML 2
      filterText 4
      filterImages 8
      filterXML 16
      filterXUL 32
      filterApps 64

The File Picker for me was very useful in my cross-platform work with XRap, not only does it make it make it easy for the use to select a folder, but there is no mix-up with the slashes with the use different platforms.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s