In this video we are going to learn about File Upload.
File upload is a very common feature that almost every website needs.
Here I will use multer module to upload file.
So first off all install the multer.
So go to the command prompt and run the command.


npm install multer


Alright now go to index.js file and require the mutler.


const multer = require('multer');


Also set the destination folder so just type here.
var storage = multer.diskStorage({
    destination: './uploads/',
    filename: function (req, file, cb) {
      crypto.pseudoRandomBytes(16, function (err, raw) {
        if (err) return cb(err)
        cb(null, raw.toString('hex') + path.extname(file.originalname))
      })
    }
  })
  var upload = multer({ storage: storage }
);

Now require the path module.


var path = require('path');


And also require the crypto.


cryptoglobal.crypto = require('crypto');


Now create a route.

app.get('upload',(req,res)=>{
res.render('upload');
});

Lets create view so goto the views folder.
And here just create a new file.
Lets say file name is upload.ejs.
Now inside the upload.ejs write the following code.

Just copy all text from contact.ejs page.
and paste inside the upload.ejs Now lets change the title.
Lets say title File Uploads.
Now create a form here.
So just write here.


<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
<title>Home</title>
<%- include('partials/head') %>
</head>
<body>
<%- include('partials/header') %>
<div class=\"container\">
<div class=\"row\">
<div class=\"col-md-12\">
<h1>Upload Form</h1>
<form method=\"POST\" enctype=\"multipart/form-data\">
<div class=\"form-control\">
<label for=\"file\">File</lable>
<input type=\"file\" name=\"file\" class=\"form-control\" />
</div>
<button type=\"submit\" name=\"submit\">Submit</a>
</form>
</div>
</div>
</div>

<%- include('partials/footer') %>
</body>
</html>



Now go to the index js file and create post route.


app.post('/upload', upload.single('file'), (req, res) => {
If(req.file){
res.send(\"File uploaded successfully!\");
}
else
{
res.send(\"File Upload Failed\")
}
});



Now goto the upload.ejs and add the action here.
So just type action=\"/upload\".
Now lets check.
So go to the command prompt and run the command.


node index.js


Now switch to the browser and just goto the url.
localhost:3000/upload.
Now select any file and click on submit.
Now you can see here the file uploaded successfully.
Lets find the file.
So go to the project and just open uploads folder and you can see here the file.
If I upload another file.
Select another file and submit.
File uploaded.
Switch to the destination folder and you can see the files.
So in this way you can upload files.