javascript - 使用 React 在同一个 Signed Url 上用新图像刷新图像
问题描述
您如何从 React 应用程序的AWS 签名 URL中提取新图像(例如在计时器上)。
图像正在使用<img src=signedurl />
这类似于这个问题,除了使用典型的缓存破坏器(例如添加随机查询字符串参数)不起作用。AWS 不允许额外的查询字符串并导致以下错误:
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>
The request signature we calculated does not match the signature you provided. Check your key and signing method.
</Message>
...
</Error>
我试图围绕它构建的结构是
- 客户端接收到 somebucket/some.jpg 的预签名 URL(在身份验证/授权之后)。
- 后端进程每 X 分钟上传一张新图片并替换 some.jpg。
- 客户端需要每 Y 分钟刷新一次并检索最新的图像。
解决方案
我能够解决这个问题。直接指向img.src
签名网址让我无法强制浏览器刷新图像。
但是,我能够通过我的 React javascript 中的 Signed Url 获取图像,将其转换为 base 64,然后将其设置img.src
为数据字符串。这可以根据需要在计时器上设置。
const url ='signed url';
// Fetch from the signed url. Ensure that the image is not retrieved from cache
const response = await fetch(url, { cache: 'no-store' });
const buffer = await response.arrayBuffer();
// Convert from buffer to base64 (thanks [devlucky][1])
let binary = '';
const bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach(b => binary += String.fromCharCode(b));
const base64 = window.btoa(binary);
const src = `data:image/jpeg;base64,${base64}`;
this.setState({ src });
<img src={this.state.src}>
推荐阅读
- javascript - 为什么多个 const 声明在 for...of 循环中起作用?
- android - 华为地图套件 - 在 getMapAsync() 之后未调用 onMapReady()
- kubernetes - Kubernetes Job Pod 进入“未知”状态
- php - 访问具有特定值的 XML 属性?
- javascript - 将对象添加到表单提交(发布)
- java - 将 utf-8 转换为阿拉伯语时的问题
- thread-safety - 如何确定哪些 Allegro 库函数是线程安全的?
- docker - Alpine Docker CMD 未按预期启动 crond
- reactjs - 如何正确组合具有无限滚动逻辑的功能组件
- geospatial - 将 rioxarray 剪辑到 shapefile 时出现 CRS 错误