Kalan's Blog

Kalan 頭像照片,在淡水拍攝,淺藍背景

四零二曜日電子報上線啦!訂閱訂起來

Software Engineer / Taiwanese / Life in Fukuoka
This blog supports RSS feed (all content), you can click RSS icon or setup through third-party service. If there are special styles such as code syntax in the technical article, it is still recommended to browse to the original website for the best experience.

Current Theme light

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

Please notice that currenly most of posts are translated by AI automatically and might contain lots of confusion. I'll gradually translate the post ASAP

Application of form tag with formData

In the previous article, we introduced the request format of multipart/form-data and the problems it aims to solve. This article will explain the problems and applications encountered in actual development.

Specifically, this article will cover the following sections related to form applications:

  • What happens behind the <form/> tag
  • The application of FormData in JavaScript
  • Combining FormData with fetch
  • How to handle file uploads in JavaScript

Revisiting the form tag

Inside the HTML form tag, there are actually many details implemented by the browser that developers sometimes overlook. Take the following example:

<form method="POST" action="/upload" enctype="multipart/form-data">
  <input type="text" name="name" />
  <input type="file"  name="file" />
  <button>
    Submit
  </button>
</form>

Without any JavaScript code, when you click the Submit button, the browser will perform the following actions for you:

  • Serialize the name and file fields in the input
  • Send an HTTP request with Content-Type: multipart/form-data using the POST method
  • Read the file and add it to the request content (if the file exists)

In the past, when single-page applications and frontend frameworks were not popular, it was common practice to fill out a form and submit it, then redirect to another page. However, as the amount of data to be filled out increased or when only certain sections needed to be updated (such as comments), it was not a good user experience to refresh the entire page every time. Therefore, the practice of using AJAX to call APIs and dynamically update data using JavaScript gradually emerged.

Desktop - 1

Although the dynamic update approach does improve the user experience, designing a good form still requires considering many details:

  • Error handling
  • State transitions
  • Data persistence
  • Accessibility

Many times, if one aspect is not done well, users would prefer to use the traditional form tag for full-page updates. For backend applications, using the <form> tag for full-page updates can often save a lot of development time and even rely on the built-in mechanisms of the browser for more stability.

Application of FormData in JavaScript

FormData defines an interface that allows developers to work with key/value pairs, most commonly used for form handling. You can declare a FormData object like this:

const formData = new FormData()
//                key     value
formData.append('name', 'Kalan');

If you put form elements into FormData, it will automatically serialize the information filled in into FormData:

<form id="form" enctype="multipart/form-data" action="/upload" method="POST">
  <input type="text" name="name" />
  <input type="file" name="file" />
  <button>Submit</button>
</form>

<script>
  const formData = new FormData(document.getElementById('form'));
  formData.get('name'); // Get the current value of the input
  formData.get('file'); // Get the current file
</script>

Application of FormData in JavaScript

In addition, if you put FormData in the body of a fetch request, the browser will automatically send it in the multipart/form-data format:

const formData = new FormData();
formData.append('name', 'Kalan');
formData.append('file', new File(['Hello World'], 'file.txt', { type: 'text/plain' }))

fetch('/upload', {
  method: 'POST',
  body: formData
})

After executing the above JavaScript code and observing the network request, you will find that even without explicitly defining the Content-Type, the browser will still send the request in the multipart/form-data format, and the serialization of form data is handled by the browser.

Sending multipart form-data requests with fetch and FormData

Summary

These two articles explain the application and practical usage of multipart/form-data. The first article explains the meaning of Content-Disposition, the purpose of the boundary, and how to construct a multipart/form-data request. The second article explains how we can use form and FormData in practice, and handle FormData and file uploads using JavaScript.

For the server-side, uploading files on a web page is also an HTTP request, so the server-side must parse the data based on the information in the headers and the format defined by multipart/form-data in order to correctly obtain the file content. Usually, these parsing tasks are handled by frameworks. However, it is worth noting here that there is no magic behind file uploads on the web, it is still based on HTTP requests.

Prev

HTML together to understand which form-data

Next

Reading Temperature and Humidity with Arduino via Web Serial API

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee