5 Steps to Implementing File Upload in Node.js
This tutorial will show you how to create an HTML file with a form and wire the form to a Node.js component. We'll run the Node.js server on a local machine.
Join the DZone community and get the full member experience.
Join For FreeWhat Is Node.js?
Node.js, also known as Node, is an open-source development platform for running JavaScript code on the server-side. Node is useful for developing applications that require a persistent connection from the browser to the server.
Node.js runs on a dedicated HTTP server and is designed to run single-threaded. Node.js applications are event-driven and run asynchronously — the Node server uses a constant event stack to process incoming requests. Node clients send small requests one after the other without waiting for a response. This is a shift from the mainstream model of running a larger, more complex process in which multiple threads run concurrently, each waiting for an appropriate response before continuing.
Developing a File Uploading Script
If your application allows users to upload files, you have two options—developing file uploading functionality yourself or leveraging a file upload service. Here are the pros and cons of scripting a file upload yourself.
The advantages of scripting are that you can develop a solution customized to your specific needs and customize the solution on an ongoing basis. You have full control over the upload process, user options, and security measures. You can ensure integration with your company's existing tools and processes, and best of all, there is no fee for software or storage services.
The disadvantages are that a file upload script needs to be maintained and updated over time, requiring additional time and resources. It is difficult to achieve the level of security that commercial software or a file upload service can provide — file upload functionality can make your apps vulnerable to serious threat vectors such as local file inclusion (LFI). Storing uploaded files on your server will result in slower uploads for users, and uploaded files will be slower to deliver to users unless you deliver them via CDN.
Despite these disadvantages, you can easily develop a simple file upload script using multiple programming languages. Here is an example showing how to build file upload in Node.js.
Node.js File Upload Example With Ajax and JavaScript
This tutorial will show you how to create an HTML file with a form and wire the form to a Node.js component. We will run the Node.js server on the local machine. See this blog post for more detailed background on file upload in Node.js and additional techniques.
Prerequisites:
- Install Node.js on the local machine
- Install the fs and formidable libraries:
npm install fs
,npm install formidable
- Verify Node.js is installed by running
node --version
- Create a project folder in the path
C:/NodeJSUploader
Step 1: Create the HTML Form
Add an index.html file in the project folder and add the following <form>
element:
<form action="http://localhost:80/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploader">
<input type="submit">
</form>
The input tag with type file lets the user select a file from the local device. The enctype=”multipart/form-data”
setting allows the form to support file upload.
With its type attribute set to file, it will render a file selector component on the webpage.
Step 2: Create the File Uploader JavaScript
In the project folder, create a file called nodeuploader.js with the following code:
let http = require('http');
let formidable = require('formidable');
let fs = require('fs');
http.createServer(function (req, res) {
let form = new formidable.IncomingForm();
form.parse(req, function (error, fields, file) {
let filepath = file.fileupload.filepath;
let mypath = 'C:/NodeJSUploader/';
mypath += file.fileupload.originalFilename;
fs.rename(filepath, mypath, function () {
res.write('File uploaded successfully');
res.end();
});
});
}).listen(80);
A few important points about this code:
- The formidable
IncomingForm
object handles file upload. It provides a parse method that lets you manage the file uploaded by the user. - We use the rename method provided by the fs library to move the uploaded file to your project directory.
Step 3: Test That the File Upload Works
Run the following command to start the node in your project folder:
node@javascript /c/NodeJSUploader
From the node command prompt, run this command to start your Node component:
$ node uploaduploader.js
Open your browser and visit the URL localhost:80/nodeuploader.
You should see the upload form. Try to upload a file, see that you get the success message, and look for it in the project folder.
Step 4: Replace Basic Form With Ajax Form
An Ajax-based upload can make your solution faster and more elegant, making it a full JavaScript uploader.
To switch the basic form we created in step one to an Ajax form, replace the form with this code:
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()" > Upload </button>
Then at the end of your index.html file, add the following inline script:
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("fileupload", fileupload.files[0]);
await fetch('http://localhost/nodeuploader', {
method: "POST",
body: formData
});
}
</script>
Conclusion
In this article, I explained the basics of automated file upload and showed a five-step process to create your own Node.js file upload script. I hope this will be useful as you build file upload functionality into your upcoming Node.js projects.
Opinions expressed by DZone contributors are their own.
Comments