Simple File Upload with Multer and Express.js in Node.js

883
SHARES
4k
VIEWS

Introduction:

Multer is a Node.js middleware, used to upload or handle multipart/form-data, on the top of Busboy. In this tutorials, I’ll explain the basic procedure of uploading files in Node.js server with multer. Let’s start our beginners example. In this example files will be saved into the file system.

Read the multer documentation to do different kinds of uploads.

REQUIREMENTS

  1. Node.js
  2. NPM
  3. Express.js

1. Setting up Development Environment

First of all, we need to configure our development environment.

The first thing to do is to start npm, our packages manager. To do so, open a new terminal, create a new repository which will contain our project, go in it and initialize npm:

$ mkdir UploadFile
$ cd UploadFile
$ npm init

In this folder create a file called app.js

touch app.js

Install those modules into your Node project with

npm install --save express multer ejs

2. Code

In app.js

const express = require('express');
const app = express();
const multer = require('multer');
const port = process.env.PORT || 3000;

const upload = multer({
  dest: 'uploads/' // this saves your file into a directory called "uploads"
}); 

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

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

// It's very crucial that the file name matches the name attribute in your html
app.post('/', upload.single('uploadFile'), (req, res) => {
  res.redirect('/');
});

app.listen(port, () => {
  console.log('Server is Listening on Port: ' + port)
});

In index.ejs

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

3. Running Example

Go to localhost:3000 to try it out.

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

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

Trending