我在jsp页面中有一个img标签,其中src路径要求传递标头参数来获取图像。我们如何实现呢?
首先,您需要发出一个设置头文件的ajax请求。然后,您需要使用一些HTML5 API将接收到的二进制数据转换为base64。最后,使用data:协议和base64数据设置映像src 。
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);
资料来源:
https://developer.mozilla.org/zh- CN/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data