Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  197] [ 1]  / answers: 1 / hits: 54486  / 10 Years ago, mon, may 12, 2014, 12:00:00

I have an img tag in jsp page where the src path requires header parameters to pass to get the image. How can we achieve it?


More From » ajax

 Answers
2

First, you'll need to make an ajax request that sets the headers. Then, you need to use some HTML5 APIs to convert binary data recieved to base64. Finally, set the image src with the data: protocol and your base64 data.



var oReq = new XMLHttpRequest();
oReq.open(GET, yourpage.jsp, true);
oReq.setRequestHeader(Your-Header-Here, Value);
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = arraybuffer;
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
var b64encoded = btoa(String.fromCharCode.apply(null, u8));
var mimetype=image/png; // or whatever your image mime type is
document.getElementById(yourimageidhere).src=data:+mimetype+;base64,+b64encoded;
}
};
oReq.send(null);


Sources:



https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data



How to convert uint8 Array to base64 Encoded String?


[#71061] Sunday, May 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elliem

Total Points: 415
Total Questions: 117
Total Answers: 94

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;