【问题标题】:How to download image to desktop with OS.File如何使用 OS.File 将图像下载到桌面
【发布时间】:2015-11-02 14:19:24
【问题描述】:

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

我想把它下载到我的高清文件夹中。

我试过了,但没有用:在这里我 XHR 并请求数据类型数组缓冲区,然后当我尝试用 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')
        }
    );
});

【问题讨论】:

    标签: firefox-addon


    【解决方案1】:

    你从我的解决方案中偷了一半: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% 异步。也许这是最好的方式。真帅!

    【讨论】:

      猜你喜欢
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      相关资源
      最近更新 更多