If you are making a system to upload images using node.js Express. And you have to convert the image to base 64 string before uploading and storing it in a directory and database.
In this tutorial guide, you will learn how to convert an image or image url to a base 64 string in node js express projects.
How to convert an Image to base64 using Node.js
By using the following steps, you can convert the image or image URL to base64 string in node js:
- Step 1: Set up Node JS Project
- Step 2: Install Express JS
- Step 3: Create the server
- Step 4: Create the HTML form
- Step 5: Handle the image upload
- Step 6: Start the server
Step 1: Set up Node JS Project
First of all, create new directory for your project and navigate to it in your command prompt or cmd. Then,execute the following command into it to initialize a new Node.js project:
cd /your-created-project-directory npm init -y
Step 2: Install Express JS
Once you have setup your node js project, now you need to execute the following command to install express
:
npm install express
Step 3: Create the server
Create a new file called server.js
and open it in a code editor. Add the following code to set up a basic Express server:
const express = require('express'); const app = express(); const port = 3000; app.use(express.static('public')); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
Step 4: Create the HTML form
Now, you need to create a new directory called public your node js project’s root directory. Inside the public
directory, create an HTML file called index.html
with the following content:
<!DOCTYPE html> <html> <head> <title>Image to Base64 Conversion - Tutsmake.com</title> </head> <body> <h1>Image to Base64 Conversion</h1> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="image" accept="image/*" /> <button type="submit">Upload</button> </form> </body> </html>
Step 5: Handle the image upload
Now, open again your server.js file and add the following code to handle the image upload and conversion to Base64:
const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('image'), (req, res) => { if (!req.file) { res.status(400).send('No file uploaded'); return; } const imageFile = req.file.path; // Convert the image to Base64 const fs = require('fs'); const base64 = fs.readFileSync(imageFile, { encoding: 'base64' }); // Send the Base64 image as a response res.send(base64); });
Step 6: Start the server
Now, save the all file and open again your cmd. Then execute the following command to start the server:
node server.js
You should see the message “Server is running on http://localhost:3000”. Open your web browser and navigateto http://localhost:3000. You should see the “Image to Base64 Conversion” page with an upload form.
Conclusion
That’s all! You have successfully learned how to convert an image or image URL to Base64 string in node js express.