首页 > 解决方案 > 使用 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>

我试图围绕它构建的结​​构是

标签: javascriptreactjsimageamazon-web-servicespre-signed-url

解决方案


我能够解决这个问题。直接指向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}>

推荐阅读