Arj*_*jun 9 javascript java ajax prototypejs
我在jsp页面中有一个img标记,其中src路径需要传递头参数来获取图像.我们怎样才能实现它?
首先,您需要创建一个设置标头的ajax请求.然后,您需要使用一些HTML5 API将收到的二进制数据转换为base64.最后,使用data:协议和base64数据设置图像src .
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);
Run Code Online (Sandbox Code Playgroud)
资料来源:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
您可以使用以下丑陋的内联黑客
<img src onerror="fetch('https://picsum.photos/200',{headers: {hello:'World!'}}).then(r=>r.blob()).then(d=> this.src=window.URL.createObjectURL(d));" />Run Code Online (Sandbox Code Playgroud)
您现在可以使用fetch()添加标头,然后将结果加载到<img>:
const src = 'https://api.mywebsite.com/profiles/123/avatar';
const options = {
headers: {
'Some-Header': '...'
}
};
fetch(src, options)
.then(res => res.blob())
.then(blob => {
imgElement.src = URL.createObjectURL(blob);
});
Run Code Online (Sandbox Code Playgroud)
您无法使用img标签访问标头参数,但有两种解决方案:
将Ajax请求与标头参数一起使用并加载图像数据
<img src="data:image/png;base64,[CODE-OF-THE-IMAHE]">
使用带有令牌的GET参数来替换此功能的标头
<img src="controller?token=[TOKEN]">
| 归档时间: |
|
| 查看次数: |
19335 次 |
| 最近记录: |