Node.js Upload File To Server

Node.js Upload File – In this Node.js Tutorial, we shall learn to Upload a File to Node.js Server from a web client. In other words a client could upload a file to Node.js Server.

To Upload File To Node.js Server, following is a step by step guide :

  1. Prerequisite modules

    We shall use http, fs and formidable modules for this example. http : for server acitivities. node fs : to save the uploaded file to a location at server. formidable : to parse html form data. If above mentioned modules are not installed already, you may install now using NPM. Run the following commands, in Terminal, to install the respective modules :

    npm installhttp npm installfs npm installformidable
  2. Prepare a HTML Form

    Prepare a HTML page (upload_file.html) with the following form, which includes input tags for file upload and form submission.

  3. Create a HTTP Server

    Create a HTTP Server that listens at port 8086 (you may change the port) and servers two urls as shown below :

  4. File Saving

    Using formidable module, parse the form elements and save the file to a location. Once file is uploaded, you may respond with a message, saying file upload is successful. Initially, files are saved to a temporary location. We may use fs.rename() method, with the new path, to move the file to a desired location.

Example for Node.js Upload File

Following is a complete working Example for Node.js Upload File

This example has two files as shown below :

Run Node.js script file in Terminal with node

The files uploaded are saved next to the node.js file, nodejs-upload-file.js. You may change this location in the node.js script file.

Open a Web browser (HTTP Client) and hit the urlhttp://localhost:8086/uploadform

Node.js Upload File - HTML Form

Click on browse.

Node.js Upload File - Select File

Select a file and click on Open.

Node.js Upload File - File Selected

Currently, the file is uploaded to the form. Click on the Upload button for the Node.js to parse the form elements and save the file.

Node.js Upload File - Successful

Check the Node.js Server, next to the node.js script file.

Conclusion :

In this Node.js Tutorial – Node.js Upload File to Server, we have learnt to use formidable, fs and http modules for uploading a file to Node.js Server.