通过jQuery AJAX接收图像并显示图像,而不需要服务器对图像进行base64编码

Receiving an image via jQuery AJAX and displaying the image without the server base64 encoding the image

本文关键字:图像 不需要 服务器 编码 base64 显示图 AJAX jQuery 通过 显示      更新时间:2023-09-26

我通过jQuery AJAX请求从我的http服务器请求图像(image/jpegimage/png):

$.ajax({
     'url': '/my/cool/api/server',
     'contentType': 'application/json',
     'data': '{"some":1,"cool":2,"request":3,"data":4}',
     'type': 'POST'
}).done(function(data) {
    // what to do here?
});

服务器返回正确的图像。我想使用src=data:image/png;base64,...语法在img标记中显示返回的图像。我不希望服务器在base64包装图像,所以我需要通过Javascript在web浏览器中这样做。我该怎么做呢?回调中的data变量似乎被弄乱了。我可以让jQuery为我返回原始图像字节吗?或者让jQuery为我编码base64的数据?

我已经得到了一个工作的香草JS版本,因此我知道原则上它是可能的。我正在寻找这个工作香草JS代码的工作jQuery变体:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/cool/api/server', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
    var arr = new Uint8Array(this.response);
    var raw = String.fromCharCode.apply(null, arr);
    var b64 = window.btoa(raw);
    var imgElem = document.getElementById('TODOImg');
    imgElem.src = 'data:image/jpeg;base64,' + b64;
};
xhr.send();

如果您想做您已经做过的事情,但使用jQuery,您或多或少都可以做到。

在jQuery的"done"函数中,你所做的与在原生XHR请求的"onload"函数中所做的完全相同。

但是,jQuery的ajax并不真正支持二进制数据,因此您可能需要将二进制传输插入其中—参见http://www.henryalgus.com/reading-binary-files-using-jquery-ajax。