In this tutorial, you will learn how to read an image file and convert it to data URI or a base64 string in node js express js applications.
How to convert an Image to base64 using Node.js
Steps to converting the image file to a base64 string or Data URI:
Step 1: Set up Node JS Project
Create new directory for your project and navigate to it in your command prompt or cmd:
cd /your-created-project-directory
npm init -y
Step 2: Set UP Express JS
Run the following command to set up express
:
npm install express
Step 3: Create the server
Create a new file called server.js
, and add the following code in it:
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
Create a new directory called public in your node js project’s root directory, Inside the public
directory, create an HTML file called index.html
:
<!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 Convert Image to Base64 String
Edit server.js
file and implement code to handle the image upload and conversion to Base64 string:
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: Test Application
Run the following command to start the server:
node server.js
Open your web browser and navigate to http://localhost:3000.
Conclusion
That’s all! You have successfully learned how to convert an image or image URL to Base64 string in node js express.