ItSolutionStuff.com

File Upload in Node JS using Multer Example

By Hardik Savani March 22, 2021
Node JS

Hello,

In this example, you will learn node js express file upload example multer. i explained simply about node.js express upload file example. This tutorial will give you simple example of node js file upload using multer. i would like to share with you node.js file uploading with multer.

I will give you step by step simple example of file upload using multer with node js and express js. let's follow bellow steps:

Preview:

Step 1: Create Node App

run bellow command and create node app.

mkdir my-app

cd my-app

npm init

Step 2: Install express and multer

run bellow command and create node app.

npm install express multer --save

Step 3: Create app.js file

app.js

const express = require('express');

const multer = require('multer');

const path = require('path');

const app = express();

const storage = multer.diskStorage({

destination: function(req, file, cb) {

cb(null, 'uploads/');

},

filename: function(req, file, cb) {

cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));

}

});

var upload = multer({ storage: storage })

app.get('/', (req, res) => {

res.sendFile(__dirname + '/index.html');

});

app.post('/', upload.single('file-to-upload'), (req, res) => {

res.redirect('/');

});

app.listen(3000);

Step 4: Create index.html file

index.html

<!DOCTYPE html>

<html lang="en">

<head>

<title>Node js Express File Upload using Multer Example - ItSolutionStuff.com</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

<h1>Node js Express File Upload using Multer Example - ItSolutionStuff.com</h1>

<form action="/" enctype="multipart/form-data" method="post">

<input type="file" name="file-to-upload">

<input type="submit" value="Upload">

</form>

</body>

</html>

now you can simply run by following command:

npm start

open following url:

localhost:3000

i hope it can help you...

Tags: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube