Application of form tag with formData

Written byKalanKalan
💡

If you have any questions or feedback, pleasefill out this form

This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.

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

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

  • What happens behind the <form/> tag
  • The application of FormData in JavaScript
  • The combination of FormData and fetch
  • How JavaScript handles file uploads

Revisit the form tag

The HTML form tag actually contains many implementation details handled by the browser that developers sometimes overlook. Consider 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 the Submit button is pressed, the browser performs the following actions:

  • Serializes the name and file fields in the input
  • Sends an HTTP request using the POST method with Content-Type: multipart/form-data
  • Reads the file and includes it in the request body (if a file exists)

In the era before single-page applications and popular front-end frameworks, it was common to submit data via a form and then redirect to another page. However, as the amount of data to be filled in increased, or when only certain areas needed to be updated (like comments), refreshing the entire page became a poor user experience. This gradually led to the practice of making API calls via AJAX and dynamically updating data with JavaScript.

Desktop - 1

While dynamic updates certainly improved user experience, creating a well-designed form requires careful consideration of many details:

  • Error handling
  • State transitions
  • Data persistence
  • Accessibility

Often, if just one aspect is not executed well, users may prefer to use a simple full-page update with a form tag instead. For backend applications, using a <form> for full-page updates can save a lot of development time and often relies on the browser's built-in mechanisms for more stable operation.

The Application of FormData in JavaScript

FormData defines an interface that makes it easy for developers to work with key/value pairs, most commonly for form handling. A declaration of FormData can be written as follows:

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

If you place the form's elements into FormData, it will automatically serialize the filled-in information directly 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

Moreover, if you place FormData in the body of a fetch request, the browser will automatically send it as multipart/form-data:

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
})

When you run the above JavaScript code and observe the Network request, you will notice that even without explicitly defining the Content-Type, the browser still sends it as multipart/form-data, with the serialization of the form data handled by the browser.

Sending multipart form-data requests with fetch and FormData

Conclusion

These two articles explained the application and practical usage of multipart/form-data. The first article discussed the meaning of Content-Disposition, the purpose of boundaries, and how to construct a multipart/form-data request. The second article described how we can practically use forms and FormData, and how to handle FormData and file uploads through JavaScript.

From the server's perspective, uploading files via a web page is also an HTTP request. Therefore, the server must parse the data according to the information in the headers and the format defined by multipart/form-data to correctly access the file content. Typically, these parsing tasks are handled by frameworks. However, it is important to note that there is no magical solution for file transmission on the web; it is fundamentally based on HTTP requests.

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

Buy me a coffee