DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Deno vs. Node.js: The Showdown Nobody Asked For But Everyone Needed
  • Building a Tic-Tac-Toe Game Using React
  • Buh-Bye, Webpack and Node.js; Hello, Rails and Import Maps
  • Bridging JavaScript and Java Packages: An Introduction to Npm2Mvn

Trending

  • Why High-Performance AI/ML Is Essential in Modern Cybersecurity
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Modern Stack for Building Scalable Systems
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  1. DZone
  2. Coding
  3. JavaScript
  4. 5 Steps to Implementing File Upload in Node.js

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.

By 
Gilad David Maayan user avatar
Gilad David Maayan
DZone Core CORE ·
Apr. 13, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
7.0K Views

Join the DZone community and get the full member experience.

Join For Free

Image of data transfer between cloud and phone

Image Source

What 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:

HTML
 
    <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:

HTML
<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:

HTML
 
<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.

JavaScript Node.js

Opinions expressed by DZone contributors are their own.

Related

  • Deno vs. Node.js: The Showdown Nobody Asked For But Everyone Needed
  • Building a Tic-Tac-Toe Game Using React
  • Buh-Bye, Webpack and Node.js; Hello, Rails and Import Maps
  • Bridging JavaScript and Java Packages: An Introduction to Npm2Mvn

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!