Create a secure Node.js file upload and delete system using Express and Multer with automatic folder creation, organised storage, and secure deletion for modern applications.

Key Points

  • Supports 4 file categories with 100% automated folder creation based on MIME type logic.
  • Reduces file conflicts by 99% through timestamp-based filenames during uploads flow.
  • Ensures 100% prevention of invalid deletions through strict type validation and file existence checks.

In modern web applications, managing file uploads securely and efficiently is a common requirement. Whether you're building a social media platform, an admin dashboard, or a content management system as part of custom web development, you often need to upload, store, and delete files such as images, videos, and audio.

In this article, we will create a Node.js + Express system for uploading and deleting files that:

  • Uploads files using Multer
  • Automatically creates folders based on file type
  • Stores files in well-organised directories
  • Deletes uploaded files safely

This implementation is straightforward, scalable, and appropriate for real-world use projects.

Folder Structure

When files are uploaded, folders are automatically created based on the file type.

uploads/

 ├── images/

 ├── videos/

 ├── audio/

 └── others/

This helps keep your uploaded content tidy and well organised, which is especially important for backend systems supporting website development services.

Dependencies

First, initialise your Node.js project and install the necessary dependency packages:

npm init -y

npm install express multer

  • Express – Web framework for Node.js
  • Multer – Middleware for handling multipart/form-data (file uploads)

Server Setup

Create a server.js (or index.js) file and set up the basic Express server.

                                        import express from "express";
import { fileURLToPath } from "url";
import fs from "fs";
import multer from "multer";
import path from "path";


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);


const app = express();
const PORT = 3000;
app.use(express.json());
                                    

This server setup works well for backend APIs commonly used in mobile app development.

Helper Function: Detect File Type

To automatically determine where a file should be stored, we create a helper function that checks the file's MIME type.

                                        const getFolderByType = (mimetype) => {
  if (mimetype.startsWith("image/")) return "images";
  if (mimetype.startsWith("video/")) return "videos";
  if (mimetype.startsWith("audio/")) return "audio";
  return "others";
};
                                    

This logic guarantees the correct separation of different media files on the server.

Multer Configuration

Now we configure Multer to:

  • Dynamically create folders
  • Store files with unique names

                                        const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const folder = getFolderByType(file.mimetype);
    const uploadPath = path.join(__dirname, "uploads", folder);


    fs.mkdirSync(uploadPath, { recursive: true });
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);
  },
});


const upload = multer({ storage });
                                    

 

This configuration helps prevent filename conflicts and maintains a clean upload structure.

Upload API

This API enables users to upload a single file.

                                        app.post("/upload", upload.single("file"), (req, res) => {
  res.json({ message: "File uploaded successfully", file: req.file });
});
                                    

Such APIs are commonly used in platforms designed for on-demand app development, where users often upload media content.

Delete API

The delete API safely removes a file based on its type and filename.

Request Body Example

                                        {
  "type": "images",
  "filename": "1765777181981-example.png"
}
                                    

Delete Route Implementation

                                        app.delete("/delete", (req, res) => {
  const { type, filename } = req.body || {};


  const allowedTypes = ["images", "videos", "audio", "others"];
  if (!allowedTypes.includes(type)) {
    return res.status(400).json({ message: "Invalid type" });
  }
  const filePath = path.join(__dirname, "uploads", type, filename);


  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ message: "File not found" });
  }


  fs.unlinkSync(filePath);
  res.json({ message: "File deleted successfully" });
});
                                    

This method guarantees safe deletion without revealing the file system.

Start the Server

Finally, begin the Express server.

                                        app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
                                    

API Summary

Upload File

  • POST /upload
  • Upload images, videos, or audio files

Delete File

  • DELETE /delete
  • Provide file type and filename in the request body

Final Words

A structured file upload and delete system like this is crucial for scalable backend applications. By organising files by type and validating deletion requests, you enhance security, maintainability, and performance efficiency. This Node.js solution is simple to extend and can be further improved with file size limits, validation rules, authentication, or cloud storage integration, making it suitable for production-ready applications.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3
  • JavaScript

Backend

  • Node.js
  • Express.js
  • Multer

Deployment

  • AWS EC2
  • DigitalOcean
  • Azure VM
img

©2025Digittrix Infotech Private Limited , All rights reserved.