File Upload Handling with Multer in MEAN Stack
File Upload Handling with Multer in MEAN Stack
Blog Article
Brief overview of file uploading in web apps
Importance of file uploads (profile pics, documents, etc.)
Introduction to Multer – middleware for handling
multipart/form-data
Overview of MEAN stack and how each layer fits in file uploading
1. Project Setup
Prerequisites:
Node.js & npm
MongoDB running
Angular CLI installed
Scaffold a basic MEAN project or use an existing one
2. Backend: Node.js + Express + Multer
a. Install Required Packages
bash
npm install express multer mongoose cors
b. Set Up Multer Middleware
js
// backend/middleware/upload.js const multer = require('multer'); const path = require('path'); // Configure storage const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); // Upload folder }, filename: (req, file, cb) => { cb(null, Date.now() + '-' + file.originalname); } }); // File filter (optional) const fileFilter = (req, file, cb) => { const allowedTypes = /jpeg|jpg|png|pdf/; const ext = allowedTypes.test(path.extname(file.originalname).toLowerCase()); if (ext) cb(null, true); else cb(new Error('Only images and PDFs are allowed')); }; const upload = multer({ storage, fileFilter }); module.exports = upload;
c. Create Upload Route
js
// backend/routes/upload.js const express = require('express'); const router = express.Router(); const upload = require('../middleware/upload'); 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;
d. Integrate Route in Server
js
// backend/server.js const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use('/uploads', express.static('uploads')); const uploadRoute = require('./routes/upload'); app.use('/api', uploadRoute); app.listen(3000, () => console.log('Server running on port 3000'));
3. Frontend: Angular File Upload Component
a. Create File Upload Component
bash
ng generate component file-upload
b. HTML Template
html
<!-- src/app/file-upload/file-upload.component.html --> <input type="file" (change)="onFileSelected($event)" /> <button (click)="onUpload()">Upload</button> <p *ngIf="uploadMsg">{{ uploadMsg }}</p>
c. Component Logic
ts
// src/app/file-upload/file-upload.component.ts import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', }) export class FileUploadComponent { selectedFile: File | null = null; uploadMsg = ''; constructor(private http: HttpClient) {} onFileSelected(event: any) { this.selectedFile = event.target.files[0]; } onUpload() { if (!this.selectedFile) return; const formData = new FormData(); formData.append('file', this.selectedFile); this.http.post<any>('http://localhost:3000/api/upload', formData) .subscribe({ next: res => this.uploadMsg = 'Upload successful!', error: err => this.uploadMsg = 'Upload failed!' }); } }
d. Enable HTTP Client in App Module
ts
// src/app/app.module.ts import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ /* ... */ ], imports: [ HttpClientModule, // ... ], }) export class AppModule {}
4. Test Your Upload Feature
Start MongoDB and Node server
Run Angular frontend (
ng serve
)
Try uploading an image or PDF
Check
/uploads
folder on backend
5. Optional Improvements
Save file metadata in MongoDB
Allow multiple file uploads
Add progress bars
Preview uploaded files
Add cloud storage (e.g., AWS S3, Cloudinary)
Conclusion
Recap of using Multer with Node for uploads
How Angular connects via
HttpClient
MEAN stack makes full-stack JS file uploads clean and modular
link https://www.achieversit.com/mean-training-course-institute-in-bangalore