Handling File Uploads with MEAN Stack
Introduction
Modern web applications often need to allow users to upload files — images, documents, or other media. In the MEAN stack (MongoDB, Express.js, Angular, Node.js), handling file uploads involves coordinating the backend (Node/Express) to receive and store files and the frontend (Angular) to send files via HTTP requests. Let’s break down how to implement file uploads in a MEAN app.
Setting Up the Backend with Node and Express
The most popular library for handling multipart/form-data in Node.js is Multer. First, install it in your project:
npm install multer
Then, configure a route to handle file uploads:
const express = require('express');
const multer = require('multer');
const router = express.Router();
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname),
});
const upload = multer({ storage });
// API endpoint
router.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).send('No file uploaded.');
res.status(200).json({ message: 'File uploaded successfully!', filePath: req.file.path });
});
module.exports = router;
This code creates an Express route /upload that saves uploaded files to an uploads/ directory and returns a success response.
Uploading Files from Angular
In your Angular component, you’ll need a file input and an HTTP request to send the selected file to the backend:
<input type="file" (change)="onFileSelected($event)" />
onFileSelected(event: any) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
this.http.post('http://localhost:3000/upload', formData).subscribe({
next: (res) => console.log('Upload success', res),
error: (err) => console.error('Upload error', err),
});
}
Here, Angular’s HttpClient sends a POST request with the file data to your Express endpoint.
Conclusion
File uploads are a common requirement in modern applications. With Multer handling uploads in Express, and Angular sending files with FormData, the MEAN stack offers a powerful solution for file handling. Always remember to validate file types and sizes for security, and consider storing files in cloud storage (like AWS S3) for scalability in production.
Learn MEAN Stack Training Course
Read more:
Building a Blog App Using MEAN Stack
Creating a Chat Application with MEAN Stack
Implementing Role-Based Authentication in MEAN Stack
Using JWT in MEAN Stack Applications
Visit Quality Thought Training Institute
Get Direction
Comments
Post a Comment