Every webpage, nowadays, 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 necessary to:

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

  • Collect crucial data from users. At times, 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 in the form of files is crucial, 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 carry out 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 goal.

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

Create a Simple Form for File Upload with HTML

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" />

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, including images, PDFs, videos, and more.

Access the Form with JavaScript

To access a form with JavaScript and obtain user inputs from it, there are several methods. 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.

Understanding 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

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

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

Prepopulate a Variable from a Form

 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 is important to note that the code above will only be valid if the submitter is a member of the form. Additionally, FormData only retrieves input 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 to which we can 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.

Note: A FormData object has the same methods whether it is prepopulated, empty, or “post populated”. Now that you have learned how to capture form input values, it’s time to learn about 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, that is, without interrupting the single-threaded execution of the JavaScript engine. The fetch method returns a promise that resolves into a Response object, from which the actual data can be extracted by calling some methods of the Response object, such as json() or text().

Here is the syntactic structure of the Fetch API:

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 of the two arguments is the resource, which is primarily a URL to a resource to be fetched. The second argument provides the custom options you want to set for your request. Please check the Fetch Global Function to learn how to customize the fetch options in detail.

Uploading a File with JavaScript

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

Here’s how:

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 utilized 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 relies on the response.

You might be wondering how the file-uploading approach in this article differs from the traditional way of uploading strictly via HTML forms. It is different because it sends well-structured form data asynchronously, unlike HTML forms that need to reload the page. Additionally, it is properly handled by the server just like HTML forms because it is an object of HTML form data, which can be sent in JSON or other formats.

The major known disadvantage of uploading files with JavaScript instead of an HTML form is that uploading won’t work if JavaScript is disabled in the browser.

FormData is supported in all modern web browsers when you don’t use its second parameter FormData('passformElement', 'dontPassSubmitter) or you 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 tend to use Axios as it is built on the Fetch API and provides a workaround for all major browsers.

Here is what our simple example would look like in your browser, with slight modifications:

Final Thoughts

Uploading a file using JavaScript plays a crucial role in enhancing user interactions. It also aids in collecting, processing, and preserving data. Many real-world problems require some of the mentioned use cases of uploading a file with JavaScript.

At this point, you should be able to access a form, utilize the FormData constructor, comprehend the Fetch API, and upload a file with JavaScript in real-world projects. Although you may need to learn form validation and encryption with JavaScript, this article provides you with a strong foundation for uploading a file using JavaScript.

Source: https://stackabuse.com/upload-a-file-using-javascript/