Example of Node.js file upload with Ajax and JavaScript

The art of file uploading is not one that has been gracefully approached in languages ​​like Java and Python. But a file upload in Node is a relatively simple undertaking, especially if you have the right NPM libraries at hand.

In this quick tutorial, I’ll show you how to upload a file from a web browser, with a server-side Node.js file upload handler and a pure Ajax-based JavaScript process on the client.

Step-by-step Node.js file download example

The basic steps followed in this example to upload a file with Node.js and JavaScript follow this order:

  1. Make sure Node.js is installed locally
  2. Create a file named upload.js
  3. Add dependencies of FileSystem (fs) and Formidable library
  4. Have Node.js parse the incoming file and move it to a preferred folder
  5. Create an HTML upload form in a file named index.js
  6. Run the JavaScript file and use the HTML form to upload the files
  7. Optionally configure the HTML page to download with Ajax and JavaScript

Node web service

The first step is to make sure that Node is installed on your computer. A quick version query will tell you whether you do or not. I will do this tutorial on version 16.13.2 of the product.

[email protected] /c/upload-example
$ node --version
v16.13.2

We want to walk before we run, so let’s first create a simple Node.js example that just spits out a status message in a browser.

Create a file named upload.js and fill it with the following code:

let http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Node JS File Uploader Checkpoint');
}).listen(80);

Open a command prompt in the same folder as the upload.js file and run the following command:

[email protected] /c/download-example
$ node upload.js

While the command is running, open a browser and navigate to localhost: 80/download

The first step in uploading files with Node is to get a simple web service running.

The text ‘Node JS File Downloader Checkpoint’ will be displayed in the browser window.

HTML 5 file downloader

In the same folder as update.jscreate another file named index.html and code an HTML 5 file uploader:

 
  <span style="color: #808080"> NodeJS File Upload Example</span>  
  
    
action="http://localhost:80/upload" method="post" enctype="multipart/form-data">             type="file" name="fileupload">      
type="submit"
>    
 

the grab label with sound type attribute set to to file will display a file picker component on the webpage.

The multipart enctype parameter on the form will allow uploading files to the server.

Open the index.html page in a browser and click the submit button. The Node.js web service will run, printing the checkpoint message to the screen.

With the web page successfully invoking the web service, it’s time to implement the Node.js JavaScript download functionality.

Install formidable and fs libraries

We will need both the filesystem (fs) and awesome libraries to help manage the Node.js file download. So stop the running server and run the following two npm install commands:

[email protected] /c/upload-example
$ npm install fs

[email protected] /c/upload-example
$ npm install formidable

JavaScript implementation of Node.js File Downloader

Now rewrite the Node.js component to use both the Formidable and the FileSystem (fs) library.

In the create a server method, we will create an instance of Formidable Incoming form object, which handles the intricacies of downloading the file.

In the Incoming form object parsing method, we use FileSystem library Rename method to move the file from its original download location to a custom folder named C:/download-example/

When the operation is complete, a ‘Successful download of Node.js file‘ message is sent to the browser.

let http = require('http');
let formidable = require('formidable');
let fs = require('fs');

http.createServer(function (req, res) {

  //Create an instance of the form object
  let form = new formidable.IncomingForm();

  //Process the file upload in Node
  form.parse(req, function (error, fields, file) {
    let filepath = file.fileupload.filepath;
    let newpath="C:/upload-example/";
    newpath += file.fileupload.originalFilename;

    //Copy the uploaded file to a custom folder
    fs.rename(filepath, newpath, function () {
      //Send a NodeJS file upload confirmation message
      res.write('NodeJS File Upload Success!');
      res.end();
    });
  });

}).listen(80);

Save this file and then run the upload.js file again.

[email protected] /c/upload-example
$ node upload.js

Then refresh the index.html page in the browser, select a file, then click Submit. The Node.js file upload process will successfully store the file on the C:/download-example/ case.

Node, Ajax and JavaScript integration

At this point, the Node.js file upload component is complete. However, some people like to perform an Ajax-based JavaScript download from the client to avoid unnecessary request-response cycles in the browser. To upload an Ajax and JavaScript file to Node.js, replace the form in the HTML page with these two lines:

id="fileupload" type="file" name="fileupload" />

And add the following script before the end body tag:

Save the index.html file and refresh the web browser. Uploads to Node.js will be done via Ajax, creating a complete JavaScript file uploader with JavaScript running on both client and server.

And it’s that simple to create a Node.js file downloader in JavaScript.

Comments are closed.