【问题标题】:createObjectURL returns undefinedcreateObjectURL 返回未定义
【发布时间】:2019-05-19 08:27:42
【问题描述】:

我的问题已被标记为与this 无关的问题。我正在尝试使用 blob 响应类型并为其创建一个 URL,而不是使用 base64 转换我的图像。

我想在 mithril.js 中复制 this 帖子中提出的代码,这是我的版本:

var getimage = function() {
    m.request({
        method: "POST",
        url: "http://localhost:8000/",
        data: gui,
        responseType: "blob",
        extract: function(xhr) {return xhr},
    })
    .then( function(result) {
        console.log(result) // displays request
        imgSrc = URL.createObjectURL( result.response ); // after this...
        // imgSrc is still set to undefined
    })
}

我的请求实际上返回一个 jpeg 图像,我可以在控制台调试器中看到(请求 > 响应),但我的变量 imgSrc 保留了 undefined 值。

这是我的调试控制台中的响应:

因此 result.response 实际上是一个二进制文件(jpeg 图像),但URL.createObjectURL 函数没有创建任何 blob。我是 javascript 新手(昨天开始),无法调试。

【问题讨论】:

标签: javascript xmlhttprequest blob mithril.js


【解决方案1】:

由于一个错误,这在 mithril.js 中尚无法实现。一个简单的解决方法是手动执行请求:

var getimage = function() {
    var oReq = new XMLHttpRequest();
    oReq.open("POST", 'http://localhost:8000/', true );
    oReq.responseType = "blob";
    oReq.onload = function ( oEvent )
    {
        URL.revokeObjectURL( imgSrc ); // revoke previous image source
        var blob = oReq.response;
        imgSrc = URL.createObjectURL( blob );
    };
    oReq.send( JSON.stringify(gui) );
}

【讨论】:

    猜你喜欢
    • 2011-10-08
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2019-12-24
    • 2016-05-15
    • 2017-03-11
    • 2019-07-09
    相关资源
    最近更新 更多