React Single File Upload with Multer and Express.js
Last Updated :
06 Aug, 2024
When we want to add functionality for uploading or deleting files, file storage becomes crucial, whether it's for website or personal use. The File Storage project using Express aims to develop a web application that provides users with a secure and efficient way to store and manage their files online. With Express, we'll be able to create a user-friendly application that allows you to upload, delete, and display your files hassle-free. Let's get started on this exciting project!
Preview of Final Output:
.png)
Prerequisites and Technologies:
- Express: Express will be used to build the entire backend for file storage.
- Multer: The Multer module will be used for uploading files.
- Ejs: EJS will be used for rendering HTML pages.
- Bootstrap: Bootstrap will be used for elegant page design and display.
Approach:
We will be utilizing Express to develop the entire backend, while the Multer module will be used for file uploads. The application will include three routes: upload, delete, and view. The upload route will be used for file uploads, the delete route will be used for deleting specific files, and the view route will be used to display all files. The HTML page will be utilized to display all files, along with the options to upload and delete. The files will be stored on the server inside the /file storage folder, and the application will support all types of files.
Functionalities:
- File Upload : This option enables user to upload a file from computer to server .
- File Delete : This option deletes the selected file stored on server if it is not found then error is thrown.
- View All Files : This option displays all the uploaded files from server on html page . The file can be viewed by clicking the link.
Steps to Create A Project:
Step 1: First we need to create react app using below command
npx create-react-app <<Project_Name>>
Step 2: Navigate to the folder
cd <<Project_Name>>
Step 3: Install the following packages using the below command.
npm install express multer ejs
Step 4: Now create app.js file in project folder. we will setup express application first create a express app instance. Configure app to use EJS. For EJS create /views folder inside project folder. This folder will consist our HTML code.
Project Structure:
Project StructureThe updated dependencies in package.json will look like this:
{
"name": "gfg-filestorage",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2",
"multer": "^1.4.5-lts.1"
}
}
Example:
- App.js: This is the main server file where we will define all the routes and starts the server to listen at port 3000
- index.ejs: This file will contain the view or template design of the project we are making and we are using EJS as a view engine.
JavaScript
// app.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'filestorage/');
},
filename: (req, file, cb) => {
const fileName = `${Date.now()}-${file.originalname}`;
cb(null, fileName);
},
});
const upload = multer({ storage });
app.use('/uploads', express.static(path.join(__dirname, 'filestorage')));
app.get('/', (req, res) => {
res.render('index')
});
app.post('/upload', upload.single('file'), (req, res) => {
res.redirect('/')
});
app.delete('/delete/:fileName', (req, res) => {
const fileName = req.params.fileName;
const filePath = path.join(__dirname, 'filestorage', fileName);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
res.send(`File "${fileName}" has been deleted.`);
} else {
res.status(404).send(`File "${fileName}" not found.`);
}
});
app.get('/view', (req, res) => {
const uploadDirectory = path.join(__dirname, 'filestorage');
fs.readdir(uploadDirectory, (err, files) => {
if (err) {
console.error(err);
res.status(500).send('Error reading the upload directory.');
} else {
res.json({ files });
}
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
JavaScript
// index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>File Storage App</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.4/umd/popper.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.min.js">
</script>
<link href=
"https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css"
rel="stylesheet">
<link href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="mt-5 text-success">GeeksForGeeks File Storage</h1>
<h2 class="mt-4">Upload File</h2>
<form action="/upload" method="POST"
enctype="multipart/form-data">
<div class="mb-3">
<input type="file" name="file"
class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>
<h2 class="mt-4">Delete File</h2>
<form id="deleteForm">
<div class="mb-3">
<select id="fileSelect" name="fileName"
class="form-select">
</select>
</div>
<button type="button" class="btn btn-danger"
onclick="deleteFile()">Delete</button>
</form>
<h2 class="mt-4">Uploaded Files</h2>
<ul id="fileList" class="list-group">
</ul>
</div>
<script>
function populateFileListWithIcons() {
fetch('/view')
.then(response => response.json())
.then(data => {
const fileList = document.getElementById('fileList');
fileList.innerHTML = '';
data.files.forEach(fileName => {
const listItem = document.createElement('li');
listItem.className = 'list-group-item d-flex justify-content-between align-items-center';
const fileExtension = fileName.split('.').pop();
const iconSpan = document.createElement('span');
iconSpan.className = 'me-3';
iconSpan.innerHTML = getFileIconHTML(fileExtension);
const fileLink = document.createElement('a');
fileLink.href = `/uploads/${fileName}`;
fileLink.textContent = fileName;
listItem.appendChild(iconSpan);
listItem.appendChild(fileLink);
fileList.appendChild(listItem);
});
})
.catch(error => console.error(error));
}
function getFileIconHTML(fileExtension) {
const iconClasses = {
pdf: 'far fa-file-pdf',
doc: 'far fa-file-word',
docx: 'far fa-file-word',
xls: 'far fa-file-excel',
xlsx: 'far fa-file-excel',
ppt: 'far fa-file-powerpoint',
pptx: 'far fa-file-powerpoint',
txt: 'far fa-file-alt',
jpg: 'far fa-file-image',
jpeg: 'far fa-file-image',
png: 'far fa-file-image',
gif: 'far fa-file-image',
default: 'far fa-file'
};
return `<i class="${iconClasses[fileExtension.toLowerCase()] || iconClasses['default']}">
</i>`;
}
function deleteFile() {
const deleteForm = document.getElementById('deleteForm');
const formData = new FormData(deleteForm);
fetch(`/delete/${formData.get('fileName')}`, {
method: 'DELETE',
})
.then(response => response.text())
.then(message => {
alert(message);
populateFileListWithIcons();
populateDeleteOptions();
})
.catch(error => console.error(error));
}
function populateDeleteOptions() {
fetch('/view')
.then(response => response.json())
.then(data => {
const fileSelect = document.getElementById('fileSelect');
fileSelect.innerHTML = '';
data.files.forEach(fileName => {
const option = document.createElement('option');
option.value = fileName;
option.textContent = fileName;
fileSelect.appendChild(option);
});
})
.catch(error => console.error(error));
}
populateFileListWithIcons();
populateDeleteOptions();
</script>
</body>
</html>
Steps to Run the application:
Step 1. Type the following command in terminal.
npm start
Step 2. Open web-browser and type the following URL
http://localhost:3000/
Output:
Similar Reads
AI and Machine Learning
Web and API Development
How to build Node.js Blog API ?In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters.Functionalities:Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we w
4 min read
RESTful Blogging API with Node and Express.jsBlogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB.Prerequisites:Node JS & NPMExpress JSMongoDBApproach t
5 min read
Build a Social Media REST API Using Node.js: A Complete GuideDevelopers build an API(Application Programming Interface) that allows other systems to interact with their Applicationâs functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and
15+ min read
Finance and Budgeting
Communication and Social Platforms
Health and Medical
Management Systems
Customer Relationship Management (CRM) System with Node.js and Express.jsCRM systems are important tools for businesses to manage their customer interactions, both with existing and potential clients. In this article, we will demonstrate how to create a CRM system using Node.js and Express. We will cover the key functionalities, prerequisites, approach, and steps require
15+ min read
Library Management Application BackendLibrary Management System backend using Express and MongoDB contains various endpoints that will help to manage library users and work with library data. The application will provide an endpoint for user management. API will be able to register users, authenticate users, borrow books, return books,
10 min read
How to Build Library Management System Using NodeJS?A Library Management System is an essential application for managing books, users, and transactions in a library. It involves adding, removing, updating, and viewing books and managing users. In this article, we will walk through how to build a simple Library Management System using NodeJS.What We A
6 min read
Student Management System using Express.js and EJS Templating EngineIn this article, we build a student management student which will have features like adding students to a record, removing students, and updating students. We will be using popular web tools NodeJS, Express JS, and MongoDB for the backend. We will use HTML, CSS, and JavaScript for the front end. We'
5 min read
Subscription Management System with NodeJS and ExpressJSIn this article, weâll walk through the step-by-step process of creating a Subscription Management System with NodeJS and ExpressJS. This application will provide users with the ability to subscribe to various plans, manage their subscriptions, and include features like user authentication and autho
5 min read
Building a Toll Road Management System using Node.jsIn this article, we are going to build a simple Toll Road Management System using Node.js, where the data will be stored in a local MongoDB database.Problem Statement: In a toll tax plaza, it is difficult to record all the transactions and store them in a single place, along with that, if required,
15+ min read
How to Build User Management System Using NodeJS?A User Management System is an essential application for handling user accounts and information. It involves creating, reading, updating, and deleting user accounts, also known as CRUD operations. In this article, we will walk through how to build a simple User Management System using NodeJS.What We
6 min read
User Management System BackendUser Management System Backend includes numerous endpoints for performing user-dealing tasks. The backend could be constructed with the use of NodeJS and MongoDB with ExpressJS . The software will offer an endpoint for consumer management. API will be capable of registering, authenticating, and cont
4 min read
File and Document Handling
Build a document generator with Express using REST APIIn the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume
2 min read
DOCX to PDF Converter using ExpressIn this article, we are going to create a Document Conversion Application that converts DOCX to PDF. We will follow step by step approach to do it. We also make use of third-party APIs.Prerequisites:Express JS multernpm Preview of the final output: Let us have a look at how the final output will loo
4 min read
How to Send Email using NodeJS?Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for
5 min read
File Sharing Platform with Node.js and Express.jsIn today's digital age, the need for efficient File sharing platforms has become increasingly prevalent. Whether it's sharing documents for collaboration or distributing media files, having a reliable solution can greatly enhance productivity and convenience. In this article, we'll explore how to cr
4 min read
React Single File Upload with Multer and Express.jsWhen we want to add functionality for uploading or deleting files, file storage becomes crucial, whether it's for website or personal use. The File Storage project using Express aims to develop a web application that provides users with a secure and efficient way to store and manage their files onli
5 min read
Entertainment and Media
Task and Project Management
Task Management System using Node and Express.jsTask Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend inter
15+ min read
Task Manager App using Express, React and GraphQL.The Task Manager app tool is designed to simplify task management with CRUD operation: creation, deletion, and modification of tasks. Users can easily generate new tasks, remove completed ones, and update task details. In this step-by-step tutorial, you will learn the process of building a Basic Tas
6 min read
Simple Task Manager CLI Using NodeJSA Task Manager is a very useful tool to keep track of your tasks, whether it's for personal use or a work-related project. In this article, we will learn how to build a Simple Task Manager CLI (Command Line Interface) application using Node.js.What We Are Going to Create?We will build a CLI task man
5 min read
Task Scheduling App with Node and Express.jsTask Scheduling app is an app that can be used to create, update, delete, and view all the tasks created. It is implemented using NodeJS and ExpressJS. The scheduler allows users to add tasks in the cache of the current session, once the app is reloaded the data gets deleted. This can be scaled usin
4 min read
Todo List CLI application using Node.jsCLI is a very powerful tool for developers. We will be learning how to create a simple Todo List application for command line. We have seen TodoList as a beginner project in web development and android development but a CLI app is something we don't often hear about.Pre-requisites:A recent version o
13 min read
Real-Time Applications