使用 React 在同一签名 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>

我试图围绕这个构建的结构是

  • 客户端接收指向某个存储桶/某些.jpg的预签名 URL(身份验证/授权后(。
  • 后端进程正在上传一个新映像并替换一些映像.jpg每 X 分钟一次。
  • 客户端需要每 Y 分钟刷新一次并检索最新的图像。

我能够解决这个问题。将img.src直接指向签名 URL 使我无法强制浏览器刷新图像。

但是,我能够通过 React javascript 中的签名 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}>

最新更新