Handling File Uploads in a MEAN App (e.g., with Multer)

 🛠️ Backend (Node.js + Express) – File Upload with Multer

1. Install Multer

bash

Copy

Edit

npm install multer

2. Set Up Multer Middleware

Create upload.js (or inside your route/controller file):


js

Copy

Edit

const multer = require('multer');

const path = require('path');


// Storage engine

const storage = multer.diskStorage({

  destination: (req, file, cb) => {

    cb(null, 'uploads/'); // make sure this folder exists

  },

  filename: (req, file, cb) => {

    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);

    cb(null, uniqueSuffix + '-' + file.originalname);

  }

});


// File filter (optional)

const fileFilter = (req, file, cb) => {

  const allowedTypes = /jpeg|jpg|png|pdf/;

  const ext = path.extname(file.originalname).toLowerCase();

  if (allowedTypes.test(ext)) {

    cb(null, true);

  } else {

    cb(new Error('Only images and PDFs are allowed'));

  }

};


const upload = multer({ storage, fileFilter });


module.exports = upload;

3. Express Route to Handle Upload

js

Copy

Edit

const express = require('express');

const router = express.Router();

const upload = require('./upload'); // import multer config


// Single file upload

router.post('/upload', upload.single('file'), (req, res) => {

  if (!req.file) return res.status(400).json({ message: 'No file uploaded' });

  res.status(200).json({

    message: 'File uploaded successfully',

    filename: req.file.filename,

    path: req.file.path

  });

});


module.exports = router;

Don't forget to mount the router in app.js or server.js:


js

Copy

Edit

const uploadRoutes = require('./routes/upload');

app.use('/api', uploadRoutes);

🧩 Frontend (Angular) – Upload File Using HttpClient

1. Angular Form

html

Copy

Edit

<form (submit)="onUpload()" enctype="multipart/form-data">

  <input type="file" (change)="onFileSelected($event)">

  <button type="submit">Upload</button>

</form>

2. Component Logic

ts

Copy

Edit

import { HttpClient } from '@angular/common/http';

import { Component } from '@angular/core';


@Component({

  selector: 'app-file-upload',

  templateUrl: './file-upload.component.html'

})

export class FileUploadComponent {

  selectedFile: File | null = null;


  constructor(private http: HttpClient) {}


  onFileSelected(event: Event) {

    const input = event.target as HTMLInputElement;

    if (input.files && input.files.length > 0) {

      this.selectedFile = input.files[0];

    }

  }


  onUpload() {

    if (!this.selectedFile) return;


    const formData = new FormData();

    formData.append('file', this.selectedFile);


    this.http.post('http://localhost:3000/api/upload', formData)

      .subscribe({

        next: (res) => console.log('Upload success:', res),

        error: (err) => console.error('Upload error:', err)

      });

  }

}

Make sure your backend allows CORS if Angular and Node run on different ports:


js

Copy

Edit

// In your Node.js app

const cors = require('cors');

app.use(cors());

✅ Output
When successful:


The file is stored in the uploads/ folder on the server.


The response includes file name and path, which can be stored in MongoDB if needed.


Optional Enhancements

Upload progress indicator in Angular (using reportProgress)


MongoDB integration (store file metadata)


Upload multiple files with upload.array('files', maxCount)


Store files in MongoDB with GridFS (if needed)

Learn MEAN Stack Course

Read More

Best Practices for Structuring a MEAN Stack Project

Angular Routing and Navigation in Single Page Applications (SPA)

Understanding Middleware in Express.js

MEAN vs. MERN: Key Differences and Use Cases

Visit Our Quality Thought Training in Hyderabad

Get Directions 

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?