如何使用OS.File将图像下载到桌面

时间:2014-08-25 18:32:05

标签: firefox-addon

我的网络上有一张图片。例如:https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1

我想将其下载到我的高清文件夹中。

我试过这个但它没有用:在这里我XHR它并请求数据类型arraybuffer,然后当我尝试用OS.File写它时我收到此错误:TypeError: Value [object ArrayBuffer] cannot be converted to a pointer osfile_shared_allthreads.jsm:443

var {Cu: utils, Cc: classes, Ci: instances} = Components;
Cu.import('resource://gre/modules/Services.jsm');
function xhr(url, cb) {
    let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);

    let handler = ev => {
        evf(m => xhr.removeEventListener(m, handler, !1));
        switch (ev.type) {
            case 'load':
                if (xhr.status == 200) {
                    cb(xhr.response);
                    break;
                }
            default:
                Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']');
                break;
        }
    };

    let evf = f => ['load', 'error', 'abort'].forEach(f);
    evf(m => xhr.addEventListener(m, handler, false));

    xhr.mozBackgroundRequest = true;
    xhr.open('GET', url, true);
    xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING;
    xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something
    xhr.send(null);
}

xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1', data => {
    Services.prompt.alert(null, 'XHR Success', data);
    var file = OS.Path.join(OS.Constants.Path.desktopDir, "test.png");
    var promised = OS.File.writeAtomic(file, data);
    promised.then(
        function() {
            alert('succesfully saved image to desktop')
        },
        function(ex) {
             alert('FAILED in saving image to desktop')
        }
    );
});

1 个答案:

答案 0 :(得分:2)

你从我的解决方案中偷了一半:https://stackoverflow.com/a/25112976/3791822

另一半来自@ nmaier的解决方案:https://stackoverflow.com/a/25148685/3791822

非常好;)

哈哈,无论如何你真的很亲近。您获得了ArrayBuffer但是将其作为Uint8Array传递给了:

var promised = OS.File.writeAtomic(file, new Uint8Array(data));

我不知道这是否是下载它的最佳方式。但它几乎100%异步。也许这是最好的方式。真酷的男人!