[英]Receiving an image via jQuery AJAX and displaying the image without the server base64 encoding the image
我通過jQuery AJAX請求從我的http服務器請求圖像( image/jpeg
或image/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在網絡瀏覽器中進行處理。 我該怎么做呢? 回調中的data
變量似乎以某種方式被破壞了。 我可以讓jQuery為我返回原始圖像字節嗎? 還是讓jQuery為我在base64中編碼數據?
我已經有一個可用的普通JS版本,因此,我原則上知道nit是可行的。 我正在搜索此正常的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的“完成”函數中,您可以完全執行本機XHR請求的“加載”功能中的操作。
但是,jQuery的ajax並不真正支持二進制數據,因此您可能需要在其中插入二進制傳輸-請參閱http://www.henryalgus.com/reading-binary-files-using-jquery-ajax 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.