Building a Node.js Express REST API for Image Upload
- Published on
- Jigar Patel--3 min read
Overview
- Introduction
- Step 1: Setting Up Your Node.js App
- Step 2: Installing Dependencies
- Step 3: Crafting the app.js File
- Running the Node.js App
- Image Upload API
- Source Code
- About the Author
- We're Hiring
- Related Blogs
Introduction
In this tutorial, we'll walk through creating a straightforward REST API for uploading images using Node.js and Multer. To accomplish this, we'll utilize popular npm packages like Express, Multer, and Body-Parser.
Node.js App
Step 1: Setting Up YourLet's start by establishing the foundation for your Node.js application:
1.Begin by crafting a new directory for your project:
mkdir my-app
cd my-app
2.Initialize your Node.js app:
npm init
Step 2: Installing Dependencies
We need to install the necessary npm packages: Express, Multer, and Body-Parser.
npm install --save express multer body-parser
app.js
File
Step 3: Crafting the Create a file named app.js
and populate it with the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const multer = require('multer');
app.use(bodyParser.json());
// Configure Multer for image upload
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
},
});
var upload = multer({ storage: storage });
// Handle image upload
app.post('/api/image-upload', upload.single('image'), (req, res) => {
const image = req.image;
res.send(apiResponse({ message: 'File uploaded successfully.', image }));
});
// API Response utility
function apiResponse(results) {
return JSON.stringify({ status: 200, error: null, response: results });
}
// Launch the server
app.listen(3000, () => {
console.log('Server started on port 3000...');
});
Running the Node.js App
1. Create an "uploads" folder at the root of your project.
2. Launch the Node.js app:
node app.js
http://localhost:3000
3. Open your web browser and navigate to: Image Upload API
Method: GET
URL: http://localhost:3000/api/image-upload
Output :
File uploaded successfully.
Source Code
The complete source code for this tutorial is available on GitHub. You can find it Here.
About the Author
Jigar Patel is a React.js enthusiast and a software developer at JBCodeapp Company. Visit our JBCodeapp to learn more about our work in the React.js ecosystem.
We're Hiring
Are you passionate about React.js development? We're always on the lookout for talented developers to join our team. Check out our Careers Page for current job openings.