• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

File Uploads with Forms in Express: A Step-by-Step Tutorial

  • June 25, 2023
  • CODE OF GEEKS
  • 0
In this tutorial ->
  • Setting up Express Project
  • Creating a Basic Form
  • Configuring File Uploads in Express
  • Handling File Uploads
  • Saving Uploaded Files
  • Handling Validation and Error Handling
  • Starting our Application
File Uploads with Forms in Express
File Uploads with Forms in Express

File uploads are a common requirement for many web applications. In this tutorial, we will explore how to handle file uploads in forms using Express.js. You will learn how to configure your Express application, handle multipart form data, and save uploaded files on the server.

By the end, you will have the knowledge to implement file upload functionality in your Express applications.



Setting up Express Project

1. Create a new directory for your project and navigate to it in your terminal:

mkdir express-app
cd express-app

2. Initialize a new npm project by running the following command and following the prompts:

npm init

3. Install Express as a dependency:

npm install express

4. Create a file named app.js (or any other preferred name) in the project directory. This will be the entry point of your Express application.

5. Open app.js in a code editor and add the following code to set up a basic Express application:

// Import the required modules
const express = require('express');
const app = express();
const port = 3000; // Choose your preferred port number

// Set up a route for the homepage
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

6. Save the file and go back to your terminal.

7. To start the Express application, run the following command:

node app.js

Once the server is up and running, you will see following message in the console:

‘Server is running on port 3000’

Open your web browser and visit http://localhost:3000 (replace 3000 with the port number you chose in the code). You should see the message “Hello, Express!” displayed in the browser.

Hello Express
Hello Express

You can stop this server by pressing CTRL+C.





Creating a Basic Form

In this step, we will create an HTML form that allows users to upload files.

<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="file" required>
  <button type="submit">Upload</button>
</form>

Inside app.js, add the following code:

const path = require('path');

app.get('/', (req, res) => {
  res.sendFile(__dirname+'/views/form.html');
});

This code sets up a route for the root path (“/”) that responds with an HTML form. The form has an input field of type “file” that allows users to select a file to upload. The form’s enctype attribute is set to "multipart/form-data" to handle file uploads.

Configuring File Uploads in Express

To handle file uploads, we need to configure Express to use a middleware that supports multipart form data. Install the multer package by running the following command:

npm install multer

Import and configure multer in app.js:

const multer = require('multer');

// Define the storage for uploaded files
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

// Create the multer middleware
const upload = multer({ storage: storage });

// Apply the middleware to the "/upload" route
app.post('/upload', upload.single('file'), (req, res) => {
  // Handle the uploaded file here
});

In this code, we configure multer to use disk storage for uploaded files. The uploaded files will be stored in the “uploads/” directory, and their original names will be preserved.

The upload.single(‘file’) middleware is applied to the “/upload” route, specifying that we expect a single file upload with the field name “file”.



Handling File Uploads

Inside the route handler for “/upload”, we can access the uploaded file using req.file. For example, to log the file details, add the following code:

app.post('/upload', upload.single('file'), (req, res) => {
  console.log('Uploaded file:', req.file);
  res.send('File uploaded successfully!');
});

This code logs the file details to the console and sends a success message to the client.

Saving Uploaded Files

To save the uploaded files permanently, we need to handle file storage on the server. Create a directory named “uploads” in your project root to store the uploaded files.

Inside app.js, add the following line at the top to enable serving static files from the “uploads” directory:

app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

This line ensures that files uploaded to the “uploads” directory are accessible through the “/uploads” URL path.

To display the uploaded file on a separate route, update the route handler for “/upload” as follows:

app.post('/upload', upload.single('file'), (req, res) => {
  console.log('Uploaded file:', req.file);
  res.send(`
    <h2>File uploaded successfully!</h2>
    <img src="/uploads/${req.file.filename}" alt="Uploaded file">
  `);
});

This code responds with an HTML message and displays the uploaded file as an image. The req.file.filename variable is used to construct the URL for the uploaded file.



Handling Validation and Error Handling

When working with file uploads, it’s essential to validate the uploaded files and handle errors. For example, you might want to check the file type, size, or perform custom validation.

Inside the “/upload” route, add your custom validation and error handling logic. For instance:

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    res.status(400).send('No file uploaded!');
    return;
  }
});

In this code, we check if a file was uploaded and return an error response if no file was found. You can add your own validation checks or perform other necessary processing.

Starting our Application

1. To test the working of our application, run the following command

node app.js

2. If the above command is executed successfully, then, you will observe following message in the console:

Server is running on port 3000

3. Once you see the above message, navigate to ‘localhost:3000’ on your browser.

4. Let’s try to upload an image file by clicking on ‘Choose File’.

5. Click on upload.

6. As per our expectation,

File uploaded successfully
File uploaded successfully

7. Let’s see if there’s anything on our uploads directory.

Yup, an image was saved under uploads folder.

Congratulations! You’ve learned how to handle file uploads in forms using Express.js. We covered configuring file uploads, handling multipart form data, saving uploaded files, and handling validation and error scenarios. By applying this knowledge, you can enhance your Express applications with file upload functionality.





Keywords to search:

Express file upload tutorial,
Handling file uploads in Express.js,
Uploading files with forms in Express,
File upload example in Express,
Multer tutorial for Express file uploads,
Saving uploaded files in Express,
Validating file uploads in Express.js,
Express file upload middleware,
Handling multipart form data in Express,
Handling large file uploads in Express,
Express file upload best practices,
Secure file uploads in Express.js,
File upload progress in Express,
Limiting file size in Express file uploads,
Express file upload error handling,
Handling multiple file uploads in Express,
Streaming file uploads in Express.js,
Client-side file upload validation with Express,
Uploading files to cloud storage in Express,
Handling file uploads in Express and MongoDB,

Tags: Client-side file upload validation with ExpressExpress file upload best practicesExpress file upload error handlingExpress file upload middlewareExpress file upload tutorialFile upload example in ExpressFile upload progress in ExpressHandling file uploads in Express and MongoDBHandling file uploads in Express.jsHandling large file uploads in ExpressHandling multipart form data in ExpressHandling multiple file uploads in ExpressLimiting file size in Express file uploadsMulter tutorial for Express file uploadsSaving uploaded files in ExpressSecure file uploads in Express.jsStreaming file uploads in Express.jsUploading files to cloud storage in ExpressUploading files with forms in ExpressValidating file uploads in Express.js
  • Previous Working with Cookies in Express: A Comprehensive Tutorial
  • Next Handling Forms with Express: A Comprehensive Tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.