使用承载令牌在 JavaScript 中加载图像 [英] Loading Image in JavaScript with Bearer token

查看:31
本文介绍了使用承载令牌在 JavaScript 中加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样在 JS 中加载图像:

I am loading an image in JS like this:

var img = new Image();
img.onload = function () {
..
};
img.src = src;

这会奏效,但我意识到我必须使用 OAuth 2 保护服务器端的图像(与应用程序的其余部分一样),这只会影响我收到 401 Unauthorized.

This will work, but I have realized that I must secure my images on the server side with OAuth 2 (as with the rest of the application) and this will effect in me simply receiving a 401 Unauthorized.

这是一个 angular 应用程序,我确实有一个拦截器,因此为服务器的所有 Angular 服务请求添加了 Authorization 标头,但当然在这种情况下 - 没有使用拦截器,因为调用不是在角度上下文中进行的.

This is an angular app and I do have an interceptor adding the Authorization header consequently for all the angular service requests to the server, but in this case of course - the interceptor is not used because the call is not made in an angular context.

关于如何将授权标头添加到获取请求的任何想法?

推荐答案

如果您在服务器端的可能性有限,也可以调用 GET XMLHttpRequest 请求使用适当的 access_token 并将图像 src 设置为 数据 URI 方案 从使用 base64 编码的响应构建,如下所示:

In case you have limited possibilies at server side it is also possible to invoke a GET XMLHttpRequest request with the appropriate access_token and set the image src with a data URI scheme build from the response encoded with base64 as follow :

var request = new XMLHttpRequest();
request.open('GET','https://dl.content.com/contentfile.jpg', true);
request.setRequestHeader('Authorization', 'Bearer ' + oauthToken.access_token);
request.responseType = 'arraybuffer';
request.onload = function(e) {
    var data = new Uint8Array(this.response);
    var raw = String.fromCharCode.apply(null, data);
    var base64 = btoa(raw);
    var src = "data:image;base64," + base64;

    document.getElementById("image").src = src;
};

request.send();

这篇关于使用承载令牌在 JavaScript 中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆