How to upload base 64 image in Nodejs Application

    Jun 17, 2019       by Pankaj Kumar
upload-base64-image-nodejs.jpg

While development in Node.js, Mostly developers uses multer package to upload the image or other type of files to server. But some time we may get the image in base64 image format.

 

So in this article, We will see how a base64 image can be uploaded to the Node.js server. Here we will user Buffer to upload files.

 

What is Buffer?

Node provides Buffer class which provides instances to store raw data similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. Buffer class is a global class that can be accessed in an application without importing the buffer module.

 

Create Node.js app and install dependencies with below command:

npm init --yes

npm i express body-parser fs mime

 

After installing above dependencies, Create a file inside project folder named server.js and put below code inside it:

 

/*
* @Author: Pankaj Kumar.
* @Date: 17 June 2019
* @Source : https://jsonworld.com/
* @Topic : base-64-image-upload
*/
 
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require('body-parser');
const fs = require('fs');
const mime = require('mime');
 
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
 
// parse application/json
app.use(bodyParser.json());
 
 
const uploadImage = async (req, res, next) => {
// to declare some path to store your converted image
var matches = req.body.base64image.match(/^data:([A-Za-z-+/]+);base64,(.+)$/),
response = {};
 
if (matches.length !== 3) {
return new Error('Invalid input string');
}
 
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
let decodedImg = response;
let imageBuffer = decodedImg.data;
let type = decodedImg.type;
let extension = mime.extension(type);
let fileName = "image." + extension;
try {
fs.writeFileSync("./images/" + fileName, imageBuffer, 'utf8');
return res.send({"status":"success"});
} catch (e) {
next(e);
}
}
 
app.post('/upload/image', uploadImage)
 
app.listen(port, () => console.log(`Server is listening on port ${port}`))

 

Run the app

Run the app with the below command:

node server.js

 

Now check everything done over postman tool with input and url like below:

base 64 image upload

 

Conclusion

So in this article, I explained how to upload base64 file in the Node.js Application. If you are new to Node.js then click here to find many demos to start the app for enterprise-level application

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

You can download complete code from here. Download Code


WHAT'S NEW

Find other similar Articles here: