使用React在同一Signed Url上用新图像刷新图像

时间:2019-04-14 06:08:55

标签: javascript reactjs image amazon-web-services pre-signed-url

如何从React应用的AWS Signed URL中提取新图像(例如在计时器上)。

正在使用<img src=signedurl />

显示图像

这类似于this question,除了使用典型的cachebreaker(例如添加随机查询字符串参数)不起作用。 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(在身份验证/授权后)到somebucket / some.jpg。
  • 后端进程正在上载新图像,并每X分钟替换一次some.jpg。
  • 客户端需要每隔Y分钟刷新一次并检索最新的图像。

1 个答案:

答案 0 :(得分:0)

我能够解决这个问题。将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}>