Node JS Tutorial - File Upload
In this tutorial, we will learn about file upload, a common feature required by almost every website.
To achieve this, we will use the Multer module, a popular Node.js module for handling file uploads.
Installing Multer
First, we need to install the Multer module. To do this, go to the command prompt and run the following command:
npm install multer
Configuring Multer
Next, go to the index.js file and require the Multer module:
const multer = require('multer');
Set the destination folder:
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 }
);
Require the Path module:
var path = require('path');
Require the Crypto module:
cryptoglobal.crypto = require('crypto');
Creating a Route
Create a route:
<!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</label>
<input type="file" name="file" class="form-control" />
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
</div>
</div>
<%- include('partials/footer') %>
</body>
</html>
Creating a View
Let's create a view. Go to the views folder and create a new file called "upload.ejs".
Inside the upload.ejs file, write the following code:
Copy the text from the contact.ejs page and paste it into the upload.ejs file. Now, let's change the title to "File Uploads".
Create a form:
app.post('/upload', upload.single('file'), (req, res) => {
If(req.file){
res.send("File uploaded successfully!");
}
else
{
res.send("File Upload Failed")
}
});
Creating a Post Route
Go to the index.js file and create a post route:
node index.js
Adding the Action
Go to the upload.ejs file and add the action:
Type "action="/upload"".
Testing the File Upload
Let's test our file upload functionality. Go to the command prompt and run the command:
placeholder_9Now, switch to the browser and go to the URL: localhost:3000/upload.
Select a file and click on submit. You should see a message indicating that the file has been uploaded successfully.
Let's find the file. Go to the project and open the uploads folder. You should see the uploaded file.
If you upload another file, select another file and submit. The file will be uploaded again.
Switch to the destination folder and you should see the uploaded files.
That's it! You have now learned how to upload files using Node.js.