TLDR;
/**
* FINAL/WORKING SOLUTION
*/
// ...
app.get('/', (req, res) => {
const s3 = new AWS.S3({
accessKeyId: '-',
secretAccessKey: '-',
region: '-',
});
const params = {
Bucket: '-',
Key: '-',
};
s3.getObject(params, (err, rest) => {
if (err) throw err;
const b64 = Buffer.from(rest.Body).toString('base64');
// CHANGE THIS IF THE IMAGE YOU ARE WORKING WITH IS .jpg OR WHATEVER
const mimeType = 'image/png'; // e.g., image/png
res.send(`<img src="data:${mimeType};base64,${b64}" />`);
});
});
// ...
ORIGINAL ANSWER
You will need to use node to 'render' the image.. aka just send the response as an <img /> tag..
// ...
app.get('/', (req, res) => {
const s3 = new AWS.S3({
accessKeyId: '-',
secretAccessKey: '-',
region: '-',
});
const params = {
Bucket: '-',
Key: '-',
};
s3.getObject(params, (err, rest) => {
if (err) throw err;
const b64 = Buffer.from(rest).toString('base64');
// NOTE:
// Because 'rest' appears to be a buffer, you might not
// need to do `Buffer.from(...)`,you may have to do something like:
/** const b64 = rest.toString('base64'); **/
const mimeType = 'image/png'; // e.g., image/png
res.send(`<img src="data:${mimeType};base64,${b64}" />`);
});
});
// ...
EDIT 1:
I believe the issue has something to do with how the data is returned to you from S3.. You may have to do something like rest.Body or rest.body - I am not sure what the object from S3 looks like.
With that being said, I saved this image locally as sample.png, and used the code below to load it - it worked just fine. This is proof the issue has something to do with how S3 is returning that data to you.
const fs = require('fs');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
// Simulate getting data from S3 (aka data as buffer)
const rest = Buffer.from(fs.readFileSync('./sample.png'));
console.log('typeof rest = ' + typeof rest + '\r\n\r\n', rest);
// typeof rest = object
//
// <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 01 34 00 00 00 a4 08 03 00 00 00 2e 4e 22 5a 00 00 00 a2 50 4c 54 45 f7 f7 f7 cd 00 00 d1 00 00 ... 6360 more bytes>
const b64 = rest.toString('base64');
const mimeType = 'image/png'; // e.g., image/png
res.send(`<img src="data:${mimeType};base64,${b64}" />`);
});
app.listen(3000);
EDIT 2:
It looks like you'll need to do this:
// ...
app.get('/', (req, res) => {
const s3 = new AWS.S3({
accessKeyId: '-',
secretAccessKey: '-',
region: '-',
});
const params = {
Bucket: '-',
Key: '-',
};
s3.getObject(params, (err, rest) => {
if (err) throw err;
const b64 = Buffer.from(rest.Body).toString('base64');
// IF THE ABOVE LINE DOES NOT WORK, TRY THIS:
// const b64 = rest.Body.toString('base64');
// CHANGE THIS IF THE IMAGE YOU ARE WORKING WITH IS .jpg OR WHATEVER
const mimeType = 'image/png'; // e.g., image/png
res.send(`<img src="data:${mimeType};base64,${b64}" />`);
});
});
// ...