In this we will learn about how we can upload a single file with node.js
using multer.
Multer
is
multipart/form-data
. We need node.js and NPM to run this application.
npm install express --save
express
, we can install multer using the following command -
npm install multer --save
npm init
command
to create the package.json
file.
<html>
<head>
<title> File Upload in Node.js using multer | nodejsera </title>
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
<div class="col-md-3">
<!-- Blank DIV -->
</div>
<div class="col-md-6 main">
<!-- Form Tag starts here -->
<!-- Action attribute is the route on backend. Method is POST -->
<form action="/" enctype="multipart/form-data" method="post">
<input class="box" type="file" name="single" id="single" /><br>
<input type="submit" id="submitDetails" name="submitDetails" value="Upload single file" /><br>
</form>
</div>
<div class="col-md-3">
<!-- Blank DIV -->
</div>
</div>
</div>
</body>
</html>
<span> Single file Uploaded successfully using multer </span>
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('single'), (req, res) => {
res.sendFile(__dirname + '/success.html');
});
app.listen(3000, () => {
console.log('Server is listening at 3000')
});
We can run the code using the following command and we will get the output shown below:
>node server.js
Server is listening at 3000
upload
folder of root directory.
In this article we learned how we can use node.js and multer to upload single file. We will learn about multiple files upload in the next part of the tutorial.