How to Upload Base 64 Image in Nodejs Application

Hey Everyone,

In this article, we will learn how a base 64 image can be uploaded to the Node.js application. Here we will use Buffer to upload files.

What is Buffer?

The Buffer class in Node.js is designed to handle raw binary data and it refers to the particular memory location in memory. It can only deal with binary data, and buffers act somewhat like arrays of integers but aren’t resizable.

Let’s start by setting up our project directory. Create a folder and name it Base64_imageupload. Open the folder with Visual Studio Code. Once inside the VS Code, open the terminal.

Create a package.json file by running:

npm init -y

Once created, Execute the following command to install express, mime, and body-parser dependencies in your node js app:

npm i express body-parser mime

After installing the above dependencies, Create an index.js file, So go to your app root directory and create it.
Now put the below code inside it:

const express = require('express');
const bodyParser = require('body-parser');
var fs = require('fs');
const mime = require('mime');
const app = express();
app.use(express.json());
const port = 3030;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/upload/image', async (req, res, file) => {
    var matches = req.body.base64image.match(/^data:([A-Za-z-+/]+);base64,(.+)$/),
        response = {};

    if (matches == null || matches.length != 3) {
        return res.send({"Message":'Invalid input string'});
    }
    response.type = matches[1];
    response.data = new Buffer.from(matches[2], 'base64');
    let imageBuffer = response.data;
    let type = response.type;
    let extension = mime.getExtension(type);
    var fileName = "image" + new Date().getTime() + "." +extension;
    try {
        fs.writeFileSync("./images/" + fileName, imageBuffer, 'utf8');
        return res.send({ "Message": "Image uploaded successfully" });
    } catch (e) {
        res.send(e);
    }
});
app.listen(port, console.log(`Listerning server at port ${port}`));

Run the app with the below command:

node index.js

Now, You have to convert the image to a base64 string for that, go to this site https://www.base64-image.de/ and upload your image. After uploading the image click on the show code button and copy the entire base64 string.

Open the postman and go to the x-www-form-urlencoded inside body and enter key as base64image and inside value paste the base64 string that you have copied above.

Output:

I hope you guys understand how I can do this. Please provides your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article.

Also Check, How to generate QR codes using node.js.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories