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

A couple of years ago I wrote a blog post on how to upload a file with formidable. I had the chance to write the upload function again, and found multer to be much easier to use. Here’s another beginner example.

This example saves your file into the file system.

Read the multer documentation to do different kinds of uploads.

1. Setup

Install those modules into your Node project with

npm install --save express multer

2. Code

app.js

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

const app = express();

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

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

app.listen(3000);

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Simple Multer Upload Example</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="file-to-upload">
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

3. Run

Go to localhost:3000 to try it out.

9 thoughts on “Simple File Upload with Express.js and Multer in Node.js”

  1. Hello Shiya,

    I’m currently working on a project where I need to upload a file to a local directory and store it. I followed your tutorial in a separate project and it worked perfectly. I then tried incorporating it into my own project and I cannot seem to make it work. This is most likely due to the architecture of my project so I tried following the documentation on multer’s page and still have gotten no where. At this point, I am completely lost on where to go from here and was wondering if you could be of any help? I have a git repo for my project – I can send the URL if you are interested in helping. If not, I understand as you are probably very busy.

    Thanks,
    Aric

        1. the main files to pay attention to would be server.js, public/partials/apply.html, public/app.js, directives/index.js. I believe those are the main relative files for it

Leave a Reply

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