Save website image using a Firefox Addon (SDK)

自闭症网瘾萝莉.ら 提交于 2020-01-07 02:33:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!