token模式请求图片资源
场景很简单,主要是接口需要认证包括图片,但是使用了前后端分离的模式,所以直接基于src模式指定图片是有问题的(权限)
解决方法
认证模式使用cookie
但是在现有的设计中不太合理,也比较费事,因为使用了spring cloud 认证在gateway
重新请求指定src图片数据
理论上肯定不能基于http 请求模式了,但是可以变向的使用http,基于ajax 请求获取数据,并赋值到img属性(blob,以及base64都是可行的)
实际上直接基于URL.createObjectUR也是可行的,而且比较灵活
简单运行
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo</title>
</head>
<body>
<img id="img" demosrc="/app.png" style="width: 200px;height: 200px;" alt="">
<script>
var img = document.getElementById('img');
var url = img.getAttribute('demosrc');
var request = new XMLHttpRequest();
request.responseType = 'blob';
request.open('get', url, true);
request.setRequestHeader('token', "ddddddddd");
request.onreadystatechange = e => {
if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
console.log(request.response)
img.src = URL.createObjectURL(request.response);
img.onload = () => {
URL.revokeObjectURL(img.src);
}
}
};
request.send(null);
</script>
</body>
</html>
- nginx 配置
使用次方法可以解决一些跨域的场景
worker_processes 1;
user root;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
lua_need_request_body on;
gzip on;
resolver 114.114.114.114 ipv6=off;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
server {
listen 80;
server_name localhost;
charset utf-8;
default_type text/html;
location / {
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
- docker-compose 文件
version: "3"
services:
app:
image: openresty/openresty:alpine
volumes:
- ./nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf
- ./index.html:/usr/local/openresty/nginx/html/index.html
- ./app.png:/usr/local/openresty/nginx/html/app.png
ports:
- "80:80"
- 效果
一些说明
为了性能以及安全,使用createObjectURL创建的对象,在不使用的时候应该释放掉可以使用URL.revokeObjectURL
参考资料
https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
https://github.com/jcblw/image-to-blob
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2019-09-29 Cortex Architecture
2019-09-29 cortex 水平扩展试用
2019-09-29 cortex 基本试用
2019-09-29 10 Unit Testing and Automation Tools and Libraries Java Programmers Should Learn
2018-09-29 nuclio kubernetes 部署
2018-09-29 nuclio dokcer 运行测试