
NodeJS File Upload Tutorial: A Complete Guide with Express and Multer
Want to learn how to handle file uploads in your NodeJS application? This guide provides a step-by-step walkthrough for building a robust backend API using Express, TypeScript, and Multer. Get ready to handle file uploads with ease!
This tutorial focuses on simple file upload functionality, saving files with their original names without file type restrictions or size limits.
Why Use NodeJS, Express, and Multer for File Uploads?
- NodeJS: A JavaScript runtime environment ideal for building scalable and efficient backend applications.
- Express: A minimalist web framework for NodeJS that simplifies routing and middleware management.
- Multer: A middleware for handling
multipart/form-data
, essential for file uploads.
Project Setup: Your File Upload API Structure
Here's the breakdown of the project's directory structure:
file-upload-api/
├── controllers/
│ └── upload.controller.ts
├── middleware/
│ └── upload.middleware.ts
├── routes/
│ └── upload.route.ts
├── services/
│ └── upload.service.ts
├── uploads/ (created automatically)
├── index.ts
├── tsconfig.json
└── package.json
Step 1: Install NodeJS Dependencies
Kickstart your project by installing the necessary packages:
Create tsconfig.json
file with the following basic configuration:
Step 2: Configure Multer Middleware for NodeJS File Upload
Create middleware/upload.middleware.ts
:
- This code sets up Multer to store uploaded files in the "uploads" directory.
- The
filename
function adds a timestamp to the original filename to prevent conflicts. - Make sure the
uploads
directory exists.
Step 3: Build the Upload Service
Create services/upload.service.ts
:
This service extracts relevant information from the uploaded file object and returns a formatted response.
Step 4: Craft the Upload Controller
Create controllers/upload.controller.ts
:
The controller checks if a file was uploaded and then utilizes the handleUploadService
to process the file and send a success response.
Step 5: Define the File Upload Route
Create routes/upload.route.ts
:
This route uses the upload.single('file')
middleware to handle a single file upload named "file".
Step 6: Initialize the Express Server for NodeJS File Upload
Create index.ts
:
This code initializes the Express server, uses the express.json()
middleware and mounts the upload route.
Test Your NodeJS File Upload API
Use Postman or a similar tool to test the API endpoint:
- Method: POST
- URL:
http://localhost:3000/api/upload/file
- Body: form-data
- Key:
file
(type: File) - Select a file from your system
- Key:
You should receive a JSON response similar to:
Conclusion
Congratulations! You've built a functional file upload API using NodeJS, Express, and Multer. This setup provides a solid foundation for more advanced file handling features. This should allow you to easily implement image uploads and more!