NodeJS: Using express-fileupload to simply upload files

Updated: February 6, 2024 By: Guest Contributor Post a comment

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.