DevelopmentOpen SourceProgrammingXRap

Having a Dialog with the nsIFilePicker

By February 20, 2009August 21st, 2013No Comments

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[“@mozilla.org/filepicker;1”]                    .createInstance(Components.interfaces.nsIFilePicker);

fp.init(window,”Select Directory”,nsIFilePicker.modeGetFolder);
var ret = fp.show();
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:
        modeOpen0
        modeSave1
        modeGetFolder2
        modeOpenMultiple3
    • fp.show – This call actually shows the File Picker dialog according to the mode you have chosen.  The return types are as follows:
      returnOK0
      returnCancel1
      returnReplace2
    • 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:
      filterAll1
      filterHTML2
      filterText4
      filterImages8
      filterXML16
      filterXUL32
      filterApps64

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