Sling Academy
Home/Node.js/NodeJS: Using express-fileupload to simply upload files

NodeJS: Using express-fileupload to simply upload files

Last updated: February 06, 2024

Introduction

Node.js, a JavaScript runtime built on Chrome’s V8 JavaScript engine, facilitates the development of highly scalable server-side applications. Coupled with Express.js, a fast, unopinionated, minimalist web framework for Node.js, developers have a powerful toolset to create web applications. One common requirement for web applications is the ability to upload files. In this tutorial, we will explore how to utilize express-fileupload, a lightweight Express middleware, to simplify file uploads in your Node.js applications.

Setting Up the Project

First, ensure you have Node.js installed. If not, download and install it from the official Node.js website. Next, create a new directory for your project and navigate into it:

$ mkdir express-fileupload-demo
$ cd express-fileupload-demo

Initialize a new Node.js project:

$ npm init -y

Install Express and express-fileupload:

$ npm install express express-fileupload

Creating an Upload Server

With our project set up, let’s create a simple file upload server. Create a file named app.js and add the following code:

const express = require('express');
const fileUpload = require('express-fileupload');

const app = express();

// Default options, no immediate file access
app.use(fileUpload());

app.post('/upload', function(req, res) {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  // The name of the input field (i.e. "fileToUpload") is used to retrieve the uploaded file
  let uploadedFile = req.files.fileToUpload;

  // Use mv() to place file on the server
  uploadedFile.mv('./uploads/' + uploadedFile.name, function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

app.listen(3000, function() {
  console.log('App is listening on port 3000!');
});

Understanding the Code

This code snippet sets up a basic Express server capable of handling POST requests to the /upload endpoint. The express-fileupload middleware automatically populates req.files with the uploaded files, making them easily accessible. The uploaded file’s mv() method is used to move the file to a designated directory on the server.

Testing the Server

To test the upload functionality, you will need a way to send a POST request with a file. This can be done using a simple HTML form or tools like Postman. Here’s an example of an HTML form:

<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" />
  <input type="submit" value="Upload File" />
</form>

Securing File Uploads

While express-fileupload simplifies file uploads, it’s important to implement security measures to prevent unauthorized access and uploads. Some security practices include:

  • Validating file types and sizes on the server-side.
  • Setting proper permissions for the upload directory.
  • Renaming uploaded files to avoid overwriting existing files or executing malicious files.

Advanced Usage

The express-fileupload middleware offers additional options and features for more complex use cases. For instance, you can limit the size of uploads, manage temporary files, or handle files in memory for further processing before saving them to the server.

Conclusion

In this tutorial, we’ve covered how to set up a simple file upload server using express-fileupload in a Node.js and Express application. We’ve also explored some best practices for securing file uploads and touched on advanced features of the middleware. With this knowledge, you can integrate file upload functionality into your Node.js applications more efficiently and securely.

Next Article: NodeJS: How to include subviews in Pug templates

Previous Article: Node.js: Escape dangerous HTML content in Pug templates

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • ExpressJS: How to render JSON in Pug templates
  • ExpressJS: How to pass variables to Pug templates