0

I have written very simple API with node.js and I want to insert images in the objects that can be accessible in the front-end anyone know how to do that?

1

1 Answer 1

1

If you want to send image as binary data, you can use res.sendFile function.

Below is an example that checks that req.user exists and then sends either JSON with a link to the image or the image itself. If the image is small it may be better to send a base64 encoded version.

app.get('/info', function(req,res){
    if(req.user){
        res.status(200).json({
            'imageName':'some image',
            'imageUrl':'/someImageUrlOnlyForAuthorizedUsers.jpg'
        });
    } else {
        res.status(401).send('Authorization required!');
    }
});

app.get('/someImageUrlOnlyForAuthorizedUsers.jpg', function(req,res){
    if(req.user){
        res.sendFile('./mySecretImage.jpg');
    } else {
        res.status(401).send('Authorization required!');
    }
});

If you want to create an object with the information in base 64 and with this insert it in the frontend, what you have to do is:

const fs = require('fs');

let buff = fs.readFileSync('/someImageUrlOnlyForAuthorizedUsers.jpg',{encoding: 'base64'});
let base64data = buff.toString('base64')

Then you can return this object in the api and once you capture it in the frontend I'll show you an example:

<img src="data:image/png;base64,"+base64data">
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much its working just one thing I want to know how can I get bunch of images by base64
Right now a solution would be to use fs.readdir and from this process each image individually as in the answer I gave you.See the next link geeksforgeeks.org/node-js-fs-readdir-method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.