Welcome folks today in this blog post we will be encoding and decoding images
from local pc
or url
to base64 code in node.js and express. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project by executing the below commands as shown below.
npm init -y
This will create the package.json file for the node.js project. Now we need to install the libraries needed using the npm
command as shown below
npm i node-base64-image
npm i image-to-base64
npm i express
npm i ejs
npm i multer
After installing all the above libraries you need to see the directory
structure of the final project as shown below
As you can see inside the views
folder we will be storing all the html
templates for the node.js app. And inside the public/uploads
folder we will be storing all the uploaded files by the user. Now after this you need to make an index.js
file which will be starting point of the node.js express app
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const express = require('express') const app = express() const port = 5000 app.use(express.static('public/uploads')) app.set('view engine','ejs') app.get('/',(req,res) => { res.render('index') }) app.listen(port,() => { console.log("App is listening on port 5000") }) |
As you can see in the above code we are starting a basic express app at the port number 5000. And then we are loading the ejs
and setting the default view engine and then make a simple get
request on the /
route. And also we are setting the public/uploads
to be the static directory because here we will be storing all the uploaded files from the user. And here we are loading the index.ejs
file which we need to define the views
folder as shown below
views/index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>base64 decode and encode in Javascript</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="text-center"> Base64 Decode & Encode </h1> <form action="/encode" method="post" enctype="multipart/form-data"> <div class="form-group container"> <label for="file">Upload File:</label> <input class="form-control" type="file" name="file" id="" required> </div> <div class="form-group container"> <button class="btn btn-danger btn-block"> Encode Image </button> </div> </form> <form action="/decode" method="post" enctype="multipart/form-data"> <div class="form-group container"> <label for="file">Upload Base64 Code File:</label> <input class="form-control" type="file" name="file" id="" required> </div> <div class="form-group container"> <button class="btn btn-danger btn-block"> Decode Image </button> </div> </form> </div> </body> </html> |
As you can see we are importing bootstrap
for styling the ui elements. And inside it we have two html
forms first one for encoding
the image file and secondly for decoding
the base64 code to image. And both the forms contain the file input
element and then we have the respective buttons to submit
the form.
Now we need to make the post
requests at the /encode
to encode the given image by the user. And also we need to make the post request at the /decode
for decoding the base64
code to image.
Uploading the File Using Multer
Now guys we will look first how basically how we can configure
multer library inside the express project. First of all you need to import the required library as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const multer = require('multer') const path = require('path') var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "public/uploads"); }, filename: function (req, file, cb) { cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname)); }, }); var upload = multer({ storage: storage }).single('file'); |
As you can see we are declaring the config
object for storing the uploaded files in multer. We are providing the upload directory which is public/uploads
and then we are giving the dynamic filename
using the Date.now() method. And then lastly we are calling the multer constructor and passing these storage
object and then allowing the user to only upload a single
file at a time.
Including the BodyParser Middleware
Now guys while we are working with forms in the browser we will need the body-parser
middleware to be included inside this express
app. This can be done as follows
1 2 3 4 5 |
const bodyparser = require('body-parser') app.use(bodyparser.urlencoded({ extended: false })) app.use(bodyparser.json()) |
Encoding Image to Base64 Text File
Now we will be the post
request to encode
the image to base64 code and download it as text
file in the browser. Just copy paste the code inside the index.js
file as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
const fs = require('fs'); const imageToBase64 = require('image-to-base64') app.post('/encode', (req, res) => { // upload the file output = Date.now() + "output.txt" upload(req, res, (err) => { if (err) { console.log("some error occured in uploading the file") return } else { console.log(req.file.path) // encode to base64 imageToBase64(req.file.path) // Path to the image .then((response) => { console.log(response); // "cGF0aC90by9maWxlLmpwZw==" fs.writeFileSync(output, response) res.download(output, () => { console.log("file is downloaded") }) }) .catch((error) => { console.log(error); // Logs an error if there was one }); } }) }) |
As you can see we are importing the fs
module to save the files inside the root directory and then we are importing the library to encode the image
to base64 text file. And inside this post
request we are using the imageToBase64()
method and inside this we are passing the input
image file and then it returns the promise
where we are getting the base64
code and after that we are saving the base64 code inside the text
file and download it as text
file as an attachment.
Decoding the Base64 Text to Image
Now we will be writing the /decode
request to actually take the base64 text file
and decode
it to convert to image file and download it as an attachment.
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const decodebase64toimage = require('node-base64-image').decode app.post('/decode', async (req, res) => { output = Date.now() + "output" upload(req, res,async (err) => { if (err) { console.log("error takes place") return } else { console.log(req.file.path) const base64code = fs.readFileSync(req.file.path, "utf8"); console.log(base64code) await decodebase64toimage(base64code, { fname: output, ext: "jpg" }); res.download(output + ".jpg", () => { console.log("file is downloaded") }) } }) }) |
As you can see in the above code we are importing decode
module wbich will decode the base64 text file
to image file. And then inside the post request we are uploading
the file first of all using multer and then after that we are decoding the base64 to jpg
image and then using the download()
method of express to download the file as an attachment inside the browser.
Full Source Code
Wrapping the blog post
this is the full source code of the index.js
file as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
const express = require('express') const app = express() const path = require('path') const bodyparser = require('body-parser') app.use(bodyparser.urlencoded({ extended: false })) const fs = require('fs'); const decodebase64toimage = require('node-base64-image').decode const imageToBase64 = require('image-to-base64') app.use(bodyparser.json()) const multer = require('multer') var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "public/uploads"); }, filename: function (req, file, cb) { cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname)); }, }); var upload = multer({ storage: storage }).single('file'); app.post('/encode', (req, res) => { // upload the file output = Date.now() + "output.txt" upload(req, res, (err) => { if (err) { console.log("some error occured in uploading the file") return } else { console.log(req.file.path) // encode to base64 imageToBase64(req.file.path) // Path to the image .then((response) => { console.log(response); // "cGF0aC90by9maWxlLmpwZw==" fs.writeFileSync(output, response) res.download(output, () => { console.log("file is downloaded") }) }) .catch((error) => { console.log(error); // Logs an error if there was one }); } }) }) app.post('/decode', async (req, res) => { output = Date.now() + "output" upload(req, res,async (err) => { if (err) { console.log("error takes place") return } else { console.log(req.file.path) const base64code = fs.readFileSync(req.file.path, "utf8"); console.log(base64code) await decodebase64toimage(base64code, { fname: output, ext: "jpg" }); res.download(output + ".jpg", () => { console.log("file is downloaded") }) } }) }) const port = 5000 app.set('view engine','ejs') app.get('/',(req,res) => { res.render('index') }) app.listen(port,() => { console.log("App is listening on port 5000") }) |