Upload Files using Node.js

Posted by: Mahesh Sabnis , on 11/22/2015, in Category Node.js
Views: 22190
Abstract: Node.js has one of the easiest file upload mechanism. In this article, we will explore the file upload module called formidable and see how to use it in an application.

File uploading is one of the common requirements of a web application. In case of Node.js, we can achieve file upload using the formidable module by Felix Geisendoerfer. This module is very easy to use and supports uploading of large files. Once the user uploads a file, this module saves the file in a specific location on our disk and we get back the path to the saved file. Some of the prominent features of this module as listed over here and are as follows:

  • Fast (~500mb/sec), non-buffering multipart parser
  • Automatically writing file uploads to disk
  • Low memory footprint
  • Graceful error handling
  • Very high test coverage

The other module we will use in our demo is fs-extra, which is used to copy the incoming file on the sever. This module contains functions to copy file, write file, etc.

 

Node.js Implementation

This application is developed using Visual Studio Code. This is a new FREE cross-platform editor for building and debugging modern web and cloud applications. We also need Node.js tools so that we can install necessary Node modules. Please visit following links to grab related information about Visual Studio Code.

https://code.visualstudio.com/Docs/editor/codebasics

https://code.visualstudio.com/Docs/runtimes/nodejs

Download Node tools from the following link https://github.com/Microsoft/nodejstools#readme

Step 1: Create a folder of the name VSCodeFileUpload on your hard drive. Open Visual Studio Code and open this folder using File > Open Folder option. In this folder, add Scripts and Pages folder.

Step 2: Since we need to use Formidable and Fs-Extra module, we need to install them along with intellisense for Node.js.

Open the Node.js Command Prompt (available if you have installed Node.js tools, as mentioned above) and navigate to the VSCodeFileUpload folder. Run the following commands for the necessary modules.

npm install -g tsd

The above command will install TypeScript definitions for the application so that we can get the necessary references for the application.

tsd node –action install

This will provide the necessary intellisense for Node.js.

npm install formidable@latest 

formidable_latest

This will install the latest formidable module. We need this module to read the uploaded file from the incoming form Post.

npm install fs-extra@latest

fsextra-latest

We will be using the above module for processing the uploaded file. We will store the posted file on the server.

Step 3: In the Pages folder add a new file, name it as app.html. In this file, add the following markup.

<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <h1>Uploading Files to Server</h1>
    <form method="POST" enctype="multipart/form-data">
        <h4>Select File to Upload:</h4>
        <input type=file name=fileData />
        <br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>

The above html file will be used by the client to upload the file. This contains <form> with method as POST.

 

Step 4: In the scripts folder, add a new file of name app.js. This will contain necessary logic for creating web server so that it can handle request of GET and POST type. To learn more, check this article https://www.dotnetcurry.com/nodejs/1203/create-web-server-nodejs. This file also contains logic for file upload and save.

//1.
var http = require('http');
var fs = require('fs');
var frd = require('formidable');
var filestore = require('fs-extra');


//2.
var server = http.createServer(function (req, resp) {
    //3.
    fs.readFile("../Pages/app.html", function (error, pgResp) {

        if (error) {
            resp.writeHead(404);
            resp.write('Contents you are looking are Not Found');
        } else {
            resp.writeHead(200, { 'Content-Type': 'text/html' });
            resp.write(pgResp);
        }

        resp.end();
    });

    //4.
    if (req.method.toLowerCase() == 'post') {

        //5.

        var fmr = new frd.IncomingForm();
        fmr.parse(req, function (err, fields, files) {
            resp.writeHead(200, { 'content-type': 'text/plain' });

        });

        fmr.on('end', function (fields, files) {
            //6.
            var tempPath = this.openedFiles[0].path;

            //7.
            var fileName = this.openedFiles[0].name;

            //8.       
            var newFileName = "../FileUpload_" + fileName;

            //9.
            filestore.copy(tempPath, newFileName, function (err) {
                if (err) {
                    console.error(err);
                } else {
                    console.log('File Uploaded');
                    resp.end('File Uploaded');
                }
            });
        });

        return;
    }
});
server.listen(5050);
console.log('Server Started.. on port 5050');

The above JavaScript code has following specifications. The following numbering matches with the comments applied in the code.

  1. Load modules for creating web sever (http), File IO (fs), detecting Post request and reading file (formidable) and copy file on the server to complete upload (fs-extra).
  2. Create a Web Server with request listener.
  3. Read the file for the specified path and if found, respond to the request.
  4. If the method is POST then process the file.
  5. Creates a new incoming form with Post data and parse the received data.
  6. Once the data is received and parsing is completed, get the temporary file path information. The parse() callback function contains information about the location of the uploaded file.
  7. Read the uploaded file name.
  8. Copy the received file on the new path.

Note: You can open the uploaded file using the createReadStream() method of the fs module and perform a series of file operations on it, for eg: zipping the file.

Step 5: Right click on app.js and select the option Open in Command Prompt, this will open the command window. On this command prompt, execute the following Command

Node app

The following result will be displayed

cmdexe

Open any browser and enter the following URL

http://localhost:5050/Pages/app.html

This will show the following result

uploading-files

Click on Choose File, and select the text file to upload. Once the file is selected, click on the Upload button. This step will show the following result on the Node Command prompt

file-uploaded

If you now check the current folder VSCodeFileUpload in Visual Studio Code or manually, you will see the file that got uploaded.

Conclusion

The formidable module of Node.js provides a simple mechanism of managing File uploads which can be easily managed on the server.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!