Steps to create Express JS Project
Step 1: Create a new directory for your project. Open a terminal and run the following commands:
mkdir express-file-upload-example
cd express-file-upload-example
Step 2: Run the following command to initialize a new Node.js project and create a package.json file.
npm init -y
Step 3: Install Express and Multer (middleware for handling file uploads) by running the following commands.
npm install express multer
Step 4: Create an ‘uploads’ directory in your project to store uploaded files.
mkdir uploads
Step 5: Create a new file named app.js in your project directory.
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"multer": "^1.4.5-lts.1"
}
Step 6: Add this code in your app.js file.
Javascript
//app.js const express = require( 'express' ); const multer = require( 'multer' ); const path = require( 'path' ); const app = express(); const port = 8000; // Set up Multer to handle file uploads const storage = multer.diskStorage({ destination: function (req, file, cb) { cb( null , 'uploads/' ); // Uploads will be stored in the 'uploads' directory }, filename: function (req, file, cb) { cb( null , Date.now() + path.extname(file.originalname)); // Unique filename to avoid overwriting } }); const upload = multer({ storage: storage }); app.get( '/' , (req, res) => { res.send( 'Hello from server' ) }) // Define the file upload endpoint app.post( '/api/files/upload' , upload.single( 'file' ), (req, res) => { // Access the uploaded file information from req.file const fileName = req.file.filename; // Store the file into file system / database (if needed) // Send the response res.status(200).json({ message: `File uploaded successfully: ${fileName}` }); }); // Start the server app.listen(port, () => { console.log(`Server is running on port ${port}`); }); |
Step 7: Open a terminal and run the following command to start your Express server.
node app.js
Your server should start and listen on port 8000.
Explanation:
In the above code we used the multer middleware to handle file uploads. The uploaded files are stored in the ‘uploads’ directory with a unique filename to avoid overwriting. The /api/files/upload endpoint is defined to handle POST requests for file uploads. The upload.single(‘file’) middleware specifies that we are expecting a single file with the field name ‘file’. The uploaded file information, such as the filename, can be accessed from “req.file”. The server responds with a JSON message indicating the success of the file upload.
How to test file uploads in Postman using Express?
In web development, handling file uploads is a major requirement for various APIs. Postman is a powerful tool used for API testing, facilitates the process of testing file uploads. In this article we will see how we can test file upload with the help of Postman.