问题
I am able to grab the URL of an image on a website, but I want to download the image to the local drive. I actually want the standard download prompt. What is the best way to do this using Firefox Addon SDK (using Javascript)?
回答1:
So using some code lifted from Firefox's nsIWebBrowserPersist docs, I cobbled this together. I don't understand some of the scope issues involved, and this does not prompt the user for where or how to save. For my purposes, it works, but I would like a better solution if there is one out there.
function DownloadImage(aURLToDownload, aSaveToFile)
{
try {
// download from: aURLToDownload
var downloadURI = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newURI(aURLToDownload, null, null);
console.log("Saving from: " + aURLToDownload);
// download destination
console.log("Saving as: " + aSaveToFile);
var outputFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
outputFile.initWithPath(aSaveToFile)
var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Ci.nsIWebBrowserPersist);
persist.progressListener = {
// onComplete: function(){
// alert("Download complete: " + aSaveToFile);
// }
onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
var percentComplete = (aCurTotalProgress/aMaxTotalProgress)*100;
console.log(percentComplete +"%");
}
// onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
// }
};
persist.saveURI(downloadURI, null, null, null, "", outputFile);
} catch (e) {
console.log(e);
}
}
来源:https://stackoverflow.com/questions/14048689/save-website-image-using-a-firefox-addon-sdk