Upload a File Using JavaScript

Every webpage today is updated without reloading the page to provide users with a smooth experience. Updating a page without reloading it is only possible with the use of JavaScript, as web browsers exclusively run JavaScript as a programming language.

Similarly, uploading a file without reloading the page is achieved with JavaScript to ensure a seamless user experience. Uploading a file using JavaScript is important for:

  • Web interaction. Two or more people can engage by sending images, videos, and various file types to one another. For example, you can email images and reply with images on Gmail due to file uploading capabilities provided by JavaScript.

  • Gathering important data from users. Occasionally, you may need to verify a person's identity before allowing them to use your services. You may ask them to upload a photo of themselves holding their identity card, or simply upload a PDF file of their bank statement. Uploading a file with JavaScript makes this possible.

  • Preserve data. Storing important memories or information as files is vital, allowing us to upload a file to the cloud for safekeeping.

  • Process data for content extraction, editing, cleaning, and updating. JavaScript is powerful enough to perform complex processing tasks such as adding filters to images, extracting text from images, and more. Uploading a file for processing can help achieve a specific objective.

Now that you understand what uploading a file with JavaScript involves and its purpose, let's build a simple application to demonstrate the process.

Create a Simple HTML Form for File Upload

The HTML form below will be used to select a file.

<form id="fileUploadForm">
   <input type="text" name="firstName" value="John" />
   File: <input type="file" name="upload" />
   <input type="submit" id="btn" />
</form>

Then, in the form, we have an input tag with its type set to file and its name set to upload. This allows uploading various file types, such as images, PDFs, videos, and more.

Access the Form Using JavaScript

To access a form using JavaScript and obtain user inputs from it, several methods are available. In this example, we use the following code:

const form = document.getElementById("fileUploadForm");
const submitter = document.getElementById("btn");

We have now accessed the entire form and its submitter using JavaScript. If you run console.log({form, submitter}), you will see the exact form and its submitter from the initial HTML content. When a user selects a file, we want to obtain the chosen file using the FormData constructor.

Explore FormData in JavaScript

FormData is a constructor that creates an object to store form inputs as key/value pairs. It uses the name property of a given input tag as a key and the entered value as its value. We can then retrieve all user input from the FormData object. It's important to note that developers often use FormData because it encodes file input.

How Does It Work?

The FormData object can be used to collect form inputs in three major ways and handle them individually.

Grab Inputs from a Specific Form After an Event

// const form = document.getElementById("fileUploadForm");
form.addEventListener("submit", (event) => { 
   const inputs = new FormData(form);  
});

Here, we access the form and its submitter, and then use the FormData object to collect all the user inputs from the form after it is submitted.

Prepopulate a Variable from a Form

// const form = document.getElementById("fileUploadForm");
// const submitter = document.getElementById("btn");
const inputs = new FormData(form, submitter); 

By passing both the form and its submitter to the FormData constructor, we automatically obtain any value entered in the form. It's important to note that the code above is only valid if the submitter is a member of the form. Additionally, FormData retrieves input only with a name and without a disabled state.

Create an Empty FormData

const inputs = new FormData();

The code snippet above constructs an empty FormData object, allowing us to add data when needed.

const inputs = new FormData();
inputs.set("name", "Ayobami");

The empty FormData is useful for structuring form input values when they are not obtained directly from a form. Visit the FormData Web API to learn more about other FormData methods.

Note: A FormData object has the same methods whether it is prepopulated, empty, or "post populated". Now that you've learned how to capture form input values, it's time to explore the Fetch API to send the file to the server.

What is the Fetch API?

The Fetch API enables a webpage to send and receive resources from a server asynchronously, without interrupting the single-threaded execution of the JavaScript engine. The fetch method returns a promise that resolves into a Response object. From this object, the actual data can be extracted by calling methods such as json() or text().

Here is the syntactic structure of the Fetch API:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

fetch(resource, options)

The Fetch API takes two arguments. The first argument is the resource, primarily a URL to a resource to be fetched. The second argument provides the custom options you want to set for your request. To learn how to customize the fetch options in detail, please visit the Fetch Global Function documentation.

Upload a File Using JavaScript

Uploading a file using JavaScript is akin to the standard form submission with JavaScript. The attributes of our file input tag specify that we want to upload a file of any type (image, video, or others).

Here's the process:

const form = document.getElementById("fileUploadForm");
const data = new FormData(form);
form.addEventListener("submit", async (event) => {
  event.preventDefault();

  let response = await fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
  });

  let result = await response.json();
  console.log(result);
});

In the code above, we obtain the selected input of a form using the FormData constructor and send it as the body of a request to the URL in the Fetch API. We set the request method to POST to transmit the data as the request body and prevent third parties from viewing the content of the request, as it is automatically encrypted by HTTPS. In short, the POST method is used to send new data to the server. Additionally, we set the request headers to indicate that the content is in JSON format and UTF-8 encoded.

The async keyword indicates that the function may take some time to execute, and the JavaScript engine should continue to process other parts of the code. Meanwhile, await instructs the engine to wait for a response before proceeding with other parts of the code, as the entire code depends on the response.

You may be curious about how the file-uploading method in this article differs from the traditional approach of uploading solely through HTML forms. The distinction lies in sending well-structured form data asynchronously, as opposed to HTML forms that require a page reload. Moreover, it is effectively managed by the server, similar to HTML forms, because it is an object of HTML form data that can be transmitted in JSON or other formats.

The primary drawback of uploading files with JavaScript rather than an HTML form is that the upload will not function if JavaScript is disabled in the browser.

FormData is supported in all modern web browsers when you don't use its second parameter, i.e FormData(formElement[, submitter]), or follow the method outlined in this article. However, some features of the Fetch API are not supported in all modern browsers, which is why developers often use Axios as it is built on the Fetch API and provides a workaround for all major browsers.

Here's what our simple example would look like in your browser, with minor modifications:

Final Considerations

Uploading a file using JavaScript significantly enhances user interactions. It also assists in collecting, processing, and preserving data. Many real-world problems necessitate some of the mentioned use cases for uploading a file with JavaScript.

At this point, you should be able to access a form, utilize the FormData constructor, understand the Fetch API, and upload a file with JavaScript in practical projects. While you may still need to learn form validation and encryption using JavaScript, this article offers a solid foundation for uploading files with JavaScript.

Last Updated: June 26th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms