Skip to content
Advertisement

Getting the image file from the server and converting it to base64 using nodejs express.js

How to create a function which gets the exact image file from the server and then converting it to base 64 and lastly storing it to a variable.

Note: Exact image file (no need to loop through the directory to list all files).

Advertisement

Answer

You can do that with the image-to-base64 library.

Installation

npm i image-to-base64

Usage

const imageToBase64 = require('image-to-base64');
//or
//import imageToBase64 from 'image-to-base64/browser';

imageToBase64("path/to/file.jpg") // Path to the image
    .then(
        (response) => {
            console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
        }
    )
    .catch(
        (error) => {
            console.log(error); // Logs an error if there was one
        }
    )

Displaying an image using base64

<img src="data:image/jpg;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" />
Advertisement