How to Upload Files with Multer

Updated at May 07, 2020

Uploading files is an essential feature for web applications these days. This tutorial will cover how to upload files into a server from the browser as well as create an API with Node.js to handle those uploads.

To simplify everything, we are going to use Express to build our API. And to handle file uploads, we are going to use Multer. Multer is an official Express middleware for handling multipart/form-data requests, which primarily used to upload files.

Getting Started

I have published the source code of this entire project. Check it out here, or clone it onto your computer with this command.

$ git clone https://github.com/rahmanfadhil/multer.git

First, we need to setup a new Node.js project for our API server. And install express and multer package.

$ npm init -y
$ npm install express multer

Setup Server

Now, we need to setup our API to handle the incoming file uploads from our front-end app.

index.js
const express = require("express")
const multer = require("multer")

const storage = multer.diskStorage({
	destination: "./uploads",
	filename(req, file, cb) {
		cb(null, Date.now() + "-" + file.originalname)
	},
})
const upload = multer({ dest: "uploads/" })
const app = express()

We first initialize an Express server, as well as a Multer instance.

We also want to create a multer storage, so that we have more control over our upload configurations. In that way, we specify the upload destination in the dest property, and generate a custom file name to a new uploaded file in the filename method.

index.js
// ...

app.use(express.static("public"))

app.post("/upload", upload.single("image"), (req, res) => {
	res.send({ filename: req.file.filename })
})

Then, we add a new express.static middleware to serve our front-end files inside the public directory.

We also want to handle every POST request from the /upload endpoint. This is where we handle our file uploads. The route should have the upload.single middleware to store the file inside the defined property, which in this case is image.

In the route handler, we will get the information of the uploaded file inside req.file property. Here, we just want to fetch the file name and send it back to the client.

Finally, can start our Express server in port 3000 (or any numbers you want).

index.js
// ...

app.listen(3000, () => {
	console.log("Server has started!")
})

Setup Client

Our server is ready to go. Now it's time to setup the front-end side of our app.

public/index.html
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>File Upload</title>
	</head>
	<body>
		<form action="/upload" method="POST" enctype="multipart/form-data">
			<input type="file" name="image" />
			<button type="submit">Upload</button>
		</form>
	</body>
</html>

The index.html file inside public folder is the home page our web app. Here, we are going to have a form which allows us to upload a single file to the /upload endpoint. Make sure that the input name is the exact as you defined your multer middleware.

We also want to make sure that the request method of our form is set to POST, and the encoding type is set to multipart/form-data. Otherwise, it won't work at all.

Now if we run our server, you will see our home page that looks like this.

ui 1

If we select a file and click upload, we will see the name of our uploaded file.

ui 2

Rahman Fadhil is an open-source developer, freelance writer, and occasional youtuber based on Jakarta.