首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用OS.File将图像下载到桌面

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

Stack Overflow用户
提问于 2014-08-25 18:32:05
回答 1查看 692关注 0票数 3

我在网上有一张图片。例如: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

代码语言:javascript
复制
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')
        }
    );
});
EN

Stack Overflow用户

回答已采纳

发布于 2014-08-25 19:02:35

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

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25492225

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档