Tuesday, August 13, 2013

Saving url to binary file with firefox addon sdk

var {Cc, Ci, components, Cu} = require('chrome');

Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

var persist = Cc['@mozilla.org/embedding/browser/nsWebBrowserPersist;1'].createInstance(Ci.nsIWebBrowserPersist);


var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
targetFile.initWithPath("/tmp/logo.png");

persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;

var uri = Cc["@mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService)
.newURI("https://developer.cdn.mozilla.net/media/img/mdn-logo-sm.png", null, null);

persist.saveURI(uri, null, null, null, "", targetFile, null);


  1. https://developer.mozilla.org/en-US/docs/Code_snippets/Downloading_Files
  2. https://developer.mozilla.org/en-US/docs/Code_snippets/Miscellaneous#Saving_an_arbitrary_URL_to_a_local_file
  3. https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/xul-migration.html
  4. http://forums.mozillazine.org/viewtopic.php?f=19&t=2015813
Update: the same with filepicker dialog:

function getDownloadFile(defaultString, fileType) {
var nsIFilePicker = Ci.nsIFilePicker;

   var fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
   var window = require("sdk/window/utils").getMostRecentBrowserWindow();
   fp.init(window, "Save As", nsIFilePicker.modeSave);
   try {
     var urlExt = defaultString.substr(defaultString.lastIndexOf(".")+1, 3);
     if (urlExt!=fileType) defaultString += "." + fileType
   }catch(ex){}

   fp.defaultString = defaultString;

   fp.appendFilter(fileType, "*." + fileType);
   var rv = fp.show();
   if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
      var file = fp.file;
      var path = fp.file.path;
      return path;
   }
   return null;
}

var {Cc, Ci, components, Cu} = require('chrome');

Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

var persist = Cc['@mozilla.org/embedding/browser/nsWebBrowserPersist;1'].createInstance(Ci.nsIWebBrowserPersist);


var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);

const file = getDownloadFile("logo.png", "png");
if (!file) {
   return;
}
targetFile.initWithPath(file);

persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE | persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;

var uri = Cc["@mozilla.org/network/io-service;1"]
.getService(Ci.nsIIOService)
  .newURI("
https://developer.cdn.mozilla.net/media/img/mdn-logo-sm.png", null, null);

persist.saveURI(uri, null, null, null, "", targetFile, null);



No comments :

Post a Comment