Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Using FormData Objects

TheFormData object lets you compile a set of key/value pairs to send using theFetch orXMLHttpRequest API. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form'ssubmit() method would use to send the data if the form's encoding type were set tomultipart/form-data.

Creating aFormData object from scratch

You can build aFormData object yourself, instantiating it then appending fields to it by calling itsappend() method, like this:

js
const send = document.querySelector("#send");send.addEventListener("click", async () => {  const formData = new FormData();  formData.append("username", "Groucho");  formData.append("accountNum", 123456);  // A file <input> element  const avatar = document.querySelector("#avatar");  formData.append("avatar", avatar.files[0]);  // JavaScript file-like object  const content = '<q><span>hey!</span></q>';  const blob = new Blob([content], { type: "text/xml" });  formData.append("webmasterFile", blob);  const response = await fetch("http://example.org/post", {    method: "POST",    body: formData,  });  console.log(await response.json());});

Note:The fields"avatar" and"webmasterFile" both contain a file. The number assigned to the field"accountNum" is immediately converted into a string by theFormData.append() method (the field's value can be aBlob,File, or a string. If the value is neither aBlob nor aFile, the value is converted to a string).

This example builds aFormData instance containing values for fields named"username","accountNum","avatar" and"webmasterFile", then usesfetch() to send the form's data. The field"webmasterFile" is aBlob. ABlob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. TheFile interface is based onBlob, inheriting blob functionality and expanding it to support files on the user's system. In order to build aBlob you can invoketheBlob() constructor.

Retrieving aFormData object from an HTML form

To construct aFormData object that contains the data from an existing<form>, specify that form element when creating theFormData object:

Note:FormData will only use input fields that use thename attribute.

js
const formData = new FormData(someFormElement);

For example:

js
const send = document.querySelector("#send");send.addEventListener("click", async () => {  // A <form> element  const userInfo = document.querySelector("#user-info");  const formData = new FormData(userInfo);  const response = await fetch("http://example.org/post", {    method: "POST",    body: formData,  });  console.log(await response.json());});

You can also append additional data to theFormData object between retrieving it from a form and sending it, like this:

js
const send = document.querySelector("#send");send.addEventListener("click", async () => {  const userInfo = document.querySelector("#user-info");  const formData = new FormData(userInfo);  formData.append("serialnumber", 12345);  const response = await fetch("http://example.org/post", {    method: "POST",    body: formData,  });  console.log(await response.json());});

This lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable.

Sending files using aFormData object

You can also send files usingFormData. Include an<input> element of typefile in your<form>:

html
<form enctype="multipart/form-data" method="post" name="fileinfo">  <p>    <label      >Your email address:      <input        type="email"        autocomplete="on"        name="userid"        placeholder="email"        required        size="32"        maxlength="64" />    </label>  </p>  <p>    <label      >Custom file label:      <input type="text" name="file-label" size="12" maxlength="32" />    </label>  </p>  <p>    <label      >File to stash:      <input type="file" name="file" required />    </label>  </p>  <p>    <input type="submit" value="Stash the file!" />  </p></form>

Then you can send it using code like the following:

js
const form = document.querySelector("#fileinfo");form.addEventListener("submit", async (event) => {  const formData = new FormData(form);  formData.append("CustomField", "This is some extra data");  const response = await fetch("stash.php", {    method: "POST",    body: formData,  });  event.preventDefault();});

Note:If you pass in a reference to the form, therequest HTTP method specified in the form will be used over the method specified in theopen() call.

Warning:When usingFormData to submit POST requests usingXMLHttpRequest or theFetch API with themultipart/form-data content type (e.g., when uploading files and blobs to the server),do not explicitly set theContent-Type header on the request. Doing so will prevent the browser from being able to set theContent-Type header with the boundary expression it will use to delimit form fields in the request body.

You can also append aFile orBlob directly to theFormData object, like this:

js
data.append("myfile", myBlob, "filename.txt");

When using theappend() method it is possible to use the third optional parameter to pass a filename inside theContent-Disposition header that is sent to the server. When no filename is specified (or the parameter isn't supported), the name "blob" is used.

Using aformdata event

Theformdata event, more recent than theFormData object, is fired on anHTMLFormElement object after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of aFormData() constructor.

This allows aFormData object to be quickly obtained in response to aformdata event firing, rather than needing to put it together yourself.

For example, in the JavaScript we can reference a form:

js
const formElem = document.querySelector("form");

In oursubmit event handler we usepreventDefault to stop the default form submission, then invoke aFormData() constructor to trigger theformdata event:

js
formElem.addEventListener("submit", (e) => {  // on form submission, prevent default  e.preventDefault();  // construct a FormData object, which fires the formdata event  new FormData(formElem);});

When theformdata event fires we can access theFormData object usingFormDataEvent.formData, then do what we like with it (below we post it to the server usingXMLHttpRequest).

js
formElem.addEventListener("formdata", (e) => {  console.log("formdata fired");  // Get the form data from the event object  const data = e.formData;  for (const value of data.values()) {    console.log(value);  }  // Submit the data via fetch()  fetch("/formHandler", {    method: "POST",    body: data,  });});

Gotchas

TheFormData object doesn't include data from the fields that are disabled or the fieldsets that are disabled.

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp