NodeJs:将存储在 AWS S3 上的图像提供给客户端 img 标签

亚历克斯

我有一个服务器和一个在 Heroku 上运行的 React 客户端。所有文件都存储在 AWS S3 上。由于文件是私有的并且需要检查身份验证,我计划通过服务器获取 URL 并将 URL 重新路由到客户端。

因此,在客户端:

<img style={{maxHeight: '10vh', width:'auto'}} src=`https://localhost:3000/api/files/${usr_id}/${filename}`/>

请注意,img 只是一个例子,但我在 AWS 上确实有其他数据类型(例如 pdf),它应该也能正常工作。

在服务器端,来自客户端的源应该通过来自 AWS 的签名 URL 直接返回图像(或其他数据)。我有第一部分,它获取签名的 URL 并且运行良好。但是想不通,如何将URL返回给客户端,使图像正常显示。

服务器端代码(简化):

  router.get('/:user/:filename', async (req, res) => {
    try {
        const url = s3.getSignedUrl('getObject', {
          Bucket: BUCKET_NAME, 
          Key: filename,
          Expires: 60 * 1,
        })
        console.log(url) // This works well and the image can be viewed in browser when copying the url
        
        // And now... ?
        // How do I return the signed URL to the image in the client?

      }
    } catch (err) {
      res.status(500).json({ message: 'Something went wrong.' });
    }
  });

提前致谢,亚历克斯

埃杜阿尔多拉贝洛

<img> 标签可以跟随重定向,例如,以 png URL 响应,您可以执行以下操作:

res.redirect(301, "/image.png");

其中最后一个参数“/image.png”是新的 URL,

这是一个工作示例,我的server.js

let express = require("express");

let app = express();

app.set("view engine", "ejs");
app.use(express.static("assets"));

app.get("/", (req, res) => {
  res.render("home");
});

app.get("/api/files/*", (req, res) => {
  let newURL = "/image.png";
  res.redirect(301, newURL);
});

app.listen(3000);

我对home.ejs 的看法

<h1>Hello World!</h1>

<!-- this path/file doesn't exist -->
<img src="/api/files/hello-world.png" alt="my image" />

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章