Reputation: 273
I have a private aws s3 container full of images I want to use on my SPA. On the backend I am using express, to try to get access to these images. This is my code on node, where I get the object from s3 container, but I don't know how to display the image from the frontend, is there a way to do this? Do I have to make my s3 container public and use the URL, I was hoping to avoid this. Thanks
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;
Could it be that I have to change the Content-Type? Since when I get the response from this, it's "application/json; charset=utf-8" when I read it in the chrome developer tool.
Upvotes: 13
Views: 23378
Reputation: 273
You can keep the bucket private, all you need to use is the getSignedURLPromise()
from the 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) });
This is literally all you need to get the URL that is safe to use, you can even put a time limit on how long its available for.
I found the answer here.
Upvotes: 7
Reputation: 41
What is your response from aws s3 looks like ? On the frontend you just have to call the api from your backend, and you will get the data as json. For example your response is like this
contents: [{
'key': 'photo1',
'url': 'www.xxxxxxx.com/photo1.png'
}]
Then what you have to do is in the frontend part you have to set the src of your img tag by url that you will receive from backend.
<img src={url} />
Upvotes: 0