Home > Software engineering >  How can I insert an image in API?
How can I insert an image in API?

Time:03-13

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?

CodePudding user response:

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">
  • Related