Simple single file upload using Node.js with Multer part 1.

GistCoding
Mar 28 · 5 min read

Today I will show you a simple and easy way to upload images using Node.js and Multer.

In part 1 of this series we will focus on getting the basic functionality working and from there, we’ll hook it up to MongoDB and also check for MIME type before uploading, making sure users only upload valid image formats and also amend filename upon upload.

What is multer? Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. You can find the Github repo here. Without further a do, lets get started.


We’ll start with some basic markup for the form, nothing fancy as we’ll be focusing on functionality first.

<div class="container p-5">
<form
action="/"
enctype="multipart/form-data"
method="post">
<div class="form-group">
<input type="file" name="file-to-upload">
</div>
<input
type="submit"
class="btn btn-primary"
value="Upload">
</form>
</div>

I used the BootstrapCDN for some basic styles. Paste the stylesheet <link> into your <head>

<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

As you can see, very straight forward markup. We have our form tag and we set the action to the home route for now. We set the enctype to multipart/form-data this is necessary as we want to allow files to be uploaded through the form.

Now for the fun part. I’ll assume you have Node.js installed. To check, open up your terminal and do node -v this should return the current version of Node.js install on your local machine.

Now lets do npm init -y this will create your package.json file and default everything to yes. Next we’ll create our our main Node.js entry file, we will call this index.js

Next we will install some dependencies. I won’t go into much detail about each dependency but I will add links for you to read up on each of them. Run the following command:

npm i express body-parser multer morgan --save

Express is the Node.js framework we’ll be using, we’ll also be using body-parser which helps us handle HTTP POST requests. multer will be used to handle file uploads and Morgan is used to log HTTP request.

Firstly we will initialise all the modules . We will also create an Express app and create a basic server.

const express = require('express')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const multer = require('multer')

TIP: Install nodemon, this is a utility that monitors changes and will restart your server automatically. Install it using the following.

npm i -g nodemon

Moving on. If we run nodemon index and navigation to http://localhost:3000 your browser should give you the following response:

Now lets get our index.html page to render so we can see our form. Replace the current app.get() with the following:

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

If you refresh your page you should see your form now.

Before we start setting up our multer config, lets first tell express where to locate our static files e.g. our custom css, javascript and images. Insert the following just below the morgan dev setup.

app.use(express.static(‘./public’))

Your file should look like this now.

const express = require('express')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const multer = require('multer')

So far so good 🙂 lets start handling the file upload using multer. Our config will look as follows. Insert the following code below our static folder setup.

const upload = multer({
dest: './public/uploads/',
limits:{
fileSize: 1000000
},
})

For now we’ll keep the config as simple as possible. All we are doing here is defining our storage location for our uploads, we set this to our static directory and in a new folder called uploads. We also set the max file size to 10MB. Now lets handle the post request, add the following code just before our server setup.

app.post('/', upload.single('file-to-upload'), (req, res, next) => {
if (!req.file) {
console.error(`No file selected`)
return res.send({
success: false
})
} else {
console.log(`File uploaded`)
res.send({
success: true,
file: req.file,
})
}
})

Ok, lets get into whats happening here. We do a POST request and we prepare our home route /to receive the file. In the request we pass in the image with upload.single('file-to-upload') . ('file-to-upload') is the name attribute we gave to the input. We first do a check to see if the file exists and if not we simply do a console.log and return a res.send() and set success to false.

if the file does exist, we do a console.log and yet again return a res.send() but this time we set the success to true and we set the file to the uploaded file. The response returned in your browser should look something like this.

When an image is received by the route, it will be automatically saved by multer to the directory you previously specified which is ./public/uploads/ .


I hope you enjoyed the post and it was helpful in some or other way, you can find the repo over here. Keep an eye out for part 2.

Please sign up to my newsletter here. I will be sending updates around the latest tools, resources and articles 🔥 for both designers and developers. Don’t worry, I only post about once or twice a month.

GistCoding

Written by

My name is Kim Petersen From the beautiful Cape Town South Africa. I have a great passion for Web Design and frontend development.