File Upload in Nodejs

FREE Online Courses: Enroll Now, Thank us Later!

Today we will be discussing how we can upload file from our device using node.js. Many different modules are available for uploading files but today we will be mainly focusing on the two most popular modules namely multer and formidable modules.

Formidable Module in Nodejs:

Install Formidable Module in Nodejs:

In order to install this module in our application run the below command

npm install formidable.

Including the module:

To use it in our project, we have to include it using the require function.

let formidable=require(‘formidable’)

Upload files using the formidable module

Create a web page for uploading Files:

We will be creating a web server using node.js which will be serving a simple form to upload files. We can go to localhost:3000 to see our web page, it contains a button to choose a file and a button to submit the uploaded file.

Code for uploading file using formidable module:

var http = require('http');
 
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
}).listen(3000);

Output

nodejs formidable server

The website will look like below

nodejs upload web page

Parsing the uploaded file:

Now we will include the formidable module and use it to parse the file. Once that is done it will be stored in a folder. Go to your localhost:3000 and upload any file, it will get uploaded and saved in a temporary folder.

Code for parsing the uploaded file using formidable module:

var http = require('http');
var formidable = require('formidable');
 
http.createServer(function (req, res) {
    if (req.url == '/fileupload') {
        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            res.write('File uploaded');
            res.end();
        });
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="filetoupload"><br>');
        res.write('<input type="submit">');
        res.write('</form>');
        return res.end();
    }
}).listen(3000);

Output

node.js parsing file

Saving the File:

Now we will be moving the file from the temporary location to our desired location.

Code for saving the file:

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
 
http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/ASUS/Documents/visual studio code/DataFlair' + files.filetoupload.name;
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(3000);

Output

nodejs saving file

You can see that a “DataFlair Demo.txt” file has been put into our DataFlair folder.

Uploading File Using Multer in Nodejs:

Multer is the most popular module for uploading files. You can upload files of any kind. Multer can be used to upload single or multiple files. It attaches the files in the request body object for uploading the files into the server.

Installing Multer:

In order to install this module in our application run the below command

npm install multer.

Including the module:

To use it in our project we have to include it using the require function.

let multer=require(‘multer’)

Uploading Files:

We will be creating a web server using node.js which will be serving a simple form to upload files. We can go to localhost:3000 to see our web page, it contains a button to choose a file and a button to submit the uploaded file.
After you upload a file you will see that a “DataFlair Multer Demo.txt” file has been added.

Code for uploading and saving a file using multer:

var http = require('http');
const multer = require('multer')
 
 
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "")
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname)
    }
})
var upload = multer({
    storage: storage,
}).single("filetoupload");
 
http.createServer(function (req, res) {
    if (req.url == '/fileupload') {
        upload(req,res,function(err){
            if(err)
            {
                res.end();
            }
            else
            {
                res.write("Success, File Uploaded!")
                res.end()
            }
        })
    } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="filetoupload"><br>');
        res.write('<input type="submit">');
        res.write('</form>');
        return res.end();
    }
}).listen(3000);

Output

node.js multer

 

Using npm file upload module:

Another way to upload a file and save it on the server is by using the file upload module:

Install:

npm i express-fileupload

Now we will be creating an HTML form for uploading the file. The code is as below

Html Code for upload page

<html>
 
<body>
    <form ref='uploadForm' id='uploadForm' action='http://localhost:3000/upload' method='post'
        encType="multipart/form-data">
        <input type="file" name="sampleFile" />
        <input type='submit' value='Upload!' />
    </form>
</body>
 
</html>

Add the below lines in the index.js file:

Code for uploading and saving the file using express-fileupload package

const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
app.use(fileUpload());
app.use('/form', express.static(__dirname + '/fileupload.html'));
app.post('/upload', function (req, res) {
    let sampleFile;
    let uploadPath;
 
    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send('No files were uploaded.');
    }
 
    sampleFile = req.files.sampleFile;
    uploadPath = __dirname + '/' + sampleFile.name;
 
    sampleFile.mv(uploadPath, function (err) {
        if (err)
            return res.status(500).send(err);
 
        res.send('File uploaded!');
    });
});
 
app.listen(3000, function () {
    console.log('Express server listening on port 3000');
});

Now if you go to localhost:3000/form and then upload a file you will see the uploaded file in your current folder, indicating that we have successfully saved the uploaded file in the server.

Output

nodejs file upload

Conclusion:

In this article, we have discussed how to upload and save the file using formidable and multer.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *