I request an image ( image/jpeg
or image/png
) from my http sever via an jQuery AJAX request:
$.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?
});
The server does return the correct image. I want to display the returned image in an img
tag using the src=data:image/png;base64,...
syntax. I don't want the server to wrap the image in base64 so I need to do it in the webbrowser via Javascript. How do I do this? The data
variable in the callback seems to be mangled somehow. Can I get jQuery to return the raw image bytes for me? Or make jQuery encode the data in base64 for me?
I already got a working vanilla JS version, thus I know in principle nit is possible. I am searching for a working jQuery variant of this working vanilla JS code:
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();
If you want to do what you've already done, but using jQuery, you're more or less there.
In jQuery's "done" function you do exactly what you would do in the "onload" function of the native XHR request.
However, jQuery's ajax doesn't really support binary data, so you might need to plug a binary transport into it - see http://www.henryalgus.com/reading-binary-files-using-jquery-ajax .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.