Saturday, June 18, 2011

Read and Write local files in Firefox

In last post (Read and Write local files in IE), we talked about how to read and write local files in IE. In this post, let’s continue this topic, and finish this function in Firefox.
The following code is about reading and writing local files in Firefox.
function readFileInFireFox(filePath) {
 try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
     alert('Unable to access local files due to browser security settings. To overcome this, follow these steps: ' + 
      '(1) Enter "about:config" in the URL field; ' + 
      '(2) Right click and select New->Boolean; ' + 
      '(3) Enter "signed.applets.codebase_principal_support" (without the quotes) as a new preference name; ' + 
      '(4) Click OK and try loading the file again.');
        return;
    }
    
    try {
  var file = Components.classes["@mozilla.org/file/local;1"]
                                .createInstance(Components.interfaces.nsILocalFile);
  file.initWithPath(filePath.replace(/\//g, "\\\\"));
  
  var is = Components.classes["@mozilla.org/network/file-input-stream;1"]
                              .createInstance(Components.interfaces.nsIFileInputStream);
  is.init(file, 0x01, 00004, null);
  
  var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
                               .createInstance(Components.interfaces.nsIScriptableInputStream);
  sis.init(is);
  
  var fileContent = sis.read(sis.available());
  
  sis.close();
  is.close();
  
  return fileContent;
    } catch (e) {
  
 }
}

function writeFileInFireFox(filePath, fileContent) {
 try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
     alert('Unable to access local files due to browser security settings. To overcome this, follow these steps: ' + 
      '(1) Enter "about:config" in the URL field; ' + 
      '(2) Right click and select New->Boolean; ' + 
      '(3) Enter "signed.applets.codebase_principal_support" (without the quotes) as a new preference name; ' + 
      '(4) Click OK and try loading the file again.');
        return;
    }
    
    try {
     var file = Components.classes["@mozilla.org/file/local;1"]
                                   .createInstance(Components.interfaces.nsILocalFile);
     file.initWithPath(filePath.replace(/\//g, "\\\\"));
     
     var os = Components.classes["@mozilla.org/network/file-output-stream;1"]
                                           .createInstance(Components.interfaces.nsIFileOutputStream);
     os.init(file, 0x04 | 0x08 | 0x20, 420, 0);
     
     os.write(fileContent, fileContent.length);
     
     os.close();
    } catch (e) {
  
 }
}

No comments:

Post a Comment