使用 React 刷新图像并同时使用新图像签名 Url
Use React to refresh image with a new one at the same Signed Url
如何从 React 应用程序的 AWS Signed URL 中提取新图像(例如在计时器上)。
正在使用 <img src=signedurl />
显示图像
这类似于 this question,除了使用典型的缓存破坏器(例如添加随机查询字符串参数)不起作用。 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>
我尝试构建的结构是
- 客户收到预签名 url(在 authentication/authorization 之后)到 somebucket/some.jpg。
- 后端进程正在上传一张新图片并每隔 X 分钟更换一次 some.jpg。
- 客户端需要每 Y 分钟刷新一次并检索最新的图像。
我能够解决这个问题。将 img.src
直接指向 Signed Url 让我无法强制浏览器刷新图像。
但是,我能够通过我的 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}>
如何从 React 应用程序的 AWS Signed URL 中提取新图像(例如在计时器上)。
正在使用 <img src=signedurl />
这类似于 this question,除了使用典型的缓存破坏器(例如添加随机查询字符串参数)不起作用。 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>
我尝试构建的结构是
- 客户收到预签名 url(在 authentication/authorization 之后)到 somebucket/some.jpg。
- 后端进程正在上传一张新图片并每隔 X 分钟更换一次 some.jpg。
- 客户端需要每 Y 分钟刷新一次并检索最新的图像。
我能够解决这个问题。将 img.src
直接指向 Signed Url 让我无法强制浏览器刷新图像。
但是,我能够通过我的 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}>