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:
- Make sure Node.js is installed locally
- Create a file named upload.js
- Add dependencies of FileSystem (fs) and Formidable library
- Have Node.js parse the incoming file and move it to a preferred folder
- Create an HTML upload form in a file named index.js
- Run the JavaScript file and use the HTML form to upload the files
- 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 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: