File Upload in Node.js using Multer

File Upload in Node.js using Multer

One essential feature of dynamic websites is to provide ease of file handling across servers. By handling I mean

  1. Browsing
  2. Fetching
  3. Uploading
  4. Storing a file Ted.jpg

In this post, I'll be sharing a procedure on how we can make use of Multer to upload files in a Node.js server and store it in the file systems.

Wait a minute... What is Multer?

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency ~ npm

NPM packages like Formidable, Multer, Multiparty, Busboy come in handy when reading or processing a multipart/form-data request on a Node.js server.
Some cases need to be considered before we use such packages -

  • If our Node.js server is backed by Express.js
  • If we want the files in the hard disk or memory

Based on these two cases, a suitable npm package that we require for file processing can be chosen.

  • Use formidable or multiparty, if the file is to be processed outside of Express.js.

    In this case, we don't have the option of storing files in memory, but only saving to temp files on disk.

  • If you want to store files in memory. It's an easy choice. Only Multer supports it.

Check this article for more info.

Enough theory 😴, we shall code it out and check for ourself😎

Prerequisites:

  • An editor of your preference (I use and recommend✌ VsCode 💖)
  • Node.js (You can download and install the LTS version from here)
  • npm (Node Package Manager)
  • Git (Optional)

Let us configure the development environment, to do that open terminal, and create a new repository/folder by the name fileUpload which will contain this small project.

$ mkdir fileUpload
$ cd fileUpload
$ npm init

Now, in this folder, we shall create some files and sub-folders required for our repository.

$ touch app.js
$ touch .gitignore
$ mkdir views && touch views/index.ejs

Note - I've created an index.ejs file as we'll be using EJS which is a
Simple templating language that lets you generate HTML markup with plain JavaScript. A template engine enables you to use static template files in your application.

We need to install the following npm packages required for our project -

  • express
  • multer
  • ejs
$ npm install --save express multer ejs

Add the node_modules file to the .gitignore in case you plan to push this project as a GitHub repository of your own.

Screenshot (40).png

Code
Inapp.js file we write the following code,

const express = require('express'),
    app = express(),
    multer = require('multer'),
    PORT = process.env.PORT || 8080;

const upload = multer({
    dest: 'uploads/', // This will save the file in directory named 'uploads'
});

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render('index');
});

// Note - File name must match the name attribute in HTML

app.post('/', upload.single('uploadFile'), (req, res) => {
    res.redirect('/');
});

app.listen(PORT, () => {
    console.log(`Server running on Port ${PORT}`);
});

The .single(field name) accepts a single file with the name field name. The single file will be stored in req.file.
To know more about this, please visit multer(opts)

In the views/index.ejs file, we shall add the following code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Multer for File Upload</title>
    </head>
    <body>
        <form action="/" enctype="multipart/form-data" method="POST">
            <input type="file" name="uploadFile" />
            <input type="submit" value="Upload" />
        </form>
    </body>
</html>

Note : The name attribute in index.ejs is same as the file name that .single() method accepts.

To check if this works, in the command line, write the command to run the app.js file:

$ node app.js

If everything checks out and there's no syntactical error we'll see on the console a message produced by app.listen():

Server running on Port 8080

Now, we shall see if our file gets uploaded successfully. To check this open the browser to visit:

localhost:8080

Click on the choose button to select the file you want to upload. Screenshot (42).png

Click on upload in the browser. Then, you'll find a new directory named uploads in our current project folder which consists of the file we uploaded.

Screenshot (44).png Conclusion:

  • Check for the case your project falls in and then make use of the best npm package for file handling.
  • There are other kinds of uploads that can be done using multer. Visit multer npm to know more.
  • You can always look out for help in the community that developed the package.
  • Code for this repository can be found here

I hope you liked this article and it helps you at some point in time.
Please do share your views in the comments.
Keep Developing and stay safe. 👋💖