开发者

Downloading files with a Firefox addon

I'm new to Firefox addon development, and it's going well so far, but I'm stuck on how to, essentially, download a file from the Web, given a URI, and save it to disk. Mozilla's MDN documentation has information on how to upload files, but the downloading files section is empty and yet to be written. Sadly, I haven't found any documentation which describes how to do this.

Does anyone know of relevant documentation on how to do this?


The old Facebook Photo Album Downloader addon uses this开发者_JAVA百科 function call in its overlay JavaScript:

saveURL(images[i].replace(/\/s/g, "/n"), null, null, false, true, null);

Obviously, the first argument is the URI to request. The saveURL function isn't defined anywhere, so I assume it's an extension API function. I have tried it in my new addon, and it does work. I would, however, like to know what the other arguments mean.


The standard way to do this is with nsIWebBrowserPersist:

var persist =
  Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
  createInstance(Ci.nsIWebBrowserPersist);
persist.saveURI(serverURI, null, null, null, "", targetFile);

See https://developer.mozilla.org/en/Code_snippets/Downloading_Files for more info.


There actually is some MDN documentation on this: https://developer.mozilla.org/en/Code_snippets/Downloading_Files.


Here's an easy copy/paste option for anyone looking for a quick solution without any further messing about. Put it in your main.js and change the filename, directory and url.

function DownloadFile(sLocalFileName, sRemoteFileName)
{
    var saveToDirectory = 'C:\\Users\\louis\\downloads\\';

    var chrome = require("chrome");

    var oIOService = chrome.Cc["@mozilla.org/network/io-service;1"].getService(chrome.Ci.nsIIOService)

    var oLocalFile = chrome.Cc["@mozilla.org/file/local;1"].createInstance(chrome.Ci.nsILocalFile);
    oLocalFile.initWithPath(saveToDirectory + sLocalFileName);

    var oDownloadObserver = {onDownloadComplete: function(nsIDownloader, nsresult, oFile) {console.log('download complete...')}};

    var oDownloader = chrome.Cc["@mozilla.org/network/downloader;1"].createInstance();
    oDownloader.QueryInterface(chrome.Ci.nsIDownloader);
    oDownloader.init(oDownloadObserver, oLocalFile);

    var oHttpChannel = oIOService.newChannel(sRemoteFileName, "", null);
    oHttpChannel.QueryInterface(chrome.Ci.nsIHttpChannel);
    oHttpChannel.asyncOpen(oDownloader, oLocalFile);    

}
DownloadFile("saveAsThis.mp3","http://domain.com/file.mp3");


As of 2015, the APIs for managing (starting, stopping, etc.) downloads have changed since this question was answered. The new APIs are (links to documentation on MDN):

  • Downloads.jsm
  • Download
  • DownloadTarget
  • PlacesUtils.There is good info at paa's answer to the question: API to modify Firefox downloads list
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜