Nodejs Serve Base64 As Image
I am trying to serve a base64 string as an image with image/png headers. The headers are being set properly but the images are not being shown all I can see is a blank screen. here
Solution 1:
The response that you are getting contains data:image/png;base64,
. You have remove this before creating the Buffer
. See example below
request('https://s3.amazonaws.com/my-trybucket/projectImages/e31492f7314837a22a64395eee7cedfd', function(error, response, body) {
var img = newBuffer(body.split(',')[1], 'base64');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
})
Solution 2:
Was stuck for long on this particular issue too only to find out that sending the actual data Body that comes back from s3 is actually sufficient to display the image. Here's my implementation (in typescript):
// a method in my Bucket classasyncgetObject(key: string) {
const params = {
Bucket: this.bucket, //my bucket name set in my constructorKey: key,
};
returnnewPromise((resolve, reject) => {
s3.getObject(params, (err, data) => {
if (err) reject(err);
if(data) resolve(data.Body);
});
});
}
// the get request route
app.get(
"url/:folder/:id",
async (req: Request, res: Response) => {
const { folder, id } = req.params;
const image = (awaitnewBucket().getObject(`${folder}/${id}`)) asBuffer;
res.send(image);
}
);
Post a Comment for "Nodejs Serve Base64 As Image"