我有一个私有(private) aws s3 容器,里面装满了我想在我的 SPA 上使用的图像。在后端,我使用 express 来尝试访问这些图像。这是我在 Node 上的代码,我从 s3 容器中获取对象,但我不知道如何从前端显示图像,有没有办法做到这一点?我是否必须公开我的 s3 容器并使用 URL,我希望避免这种情况。谢谢
let express = require('express')
let router = express.Router();
const aws = require('aws-sdk');
require('dotenv').config();
router.get('/', async (req,res) => {
try{
aws.config.setPromisesDependency(); //use so you can promisify to get the actual images
aws.config.update({
accessKeyId: process.env.ACCESSKEYID,
secretAccessKey: process.env.SECRETACCESSKEY,
region: 'us-east-1'
});
const s3 = new aws.S3();
const list = await s3.listObjectsV2({
Bucket: 'xxx-xxx-xxx'
}).promise()
res.send(list)
} catch(e) {
console.log('our error is',e)
}
})
module.exports = router;
可能是我必须更改 Content-Type 吗?因为当我从中得到响应时,当我在 chrome 开发人员工具中读取它时,它是“application/json; charset=utf-8”。
最佳答案
您可以将存储桶保密,您只需要使用 getSignedURLPromise()
来自 aws-SDK。
var params = {Bucket: 'xxx-xx-xxx', Key: '1.jpg'};
var promise = s3.getSignedUrlPromise('getObject', params);
promise.then(function(url) {
res.send(url)
}, function(err) { console.log(err) });
这实际上就是获取可安全使用的 URL 所需的全部内容,您甚至可以对其可用时长设置时间限制。我找到了答案 here .
关于node.js - 尝试将存储在 aws S3 中的图像显示到 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64473757/