New formdata

A FormData object is used to send form data to a server. It allows you to easily send form data, such as text, files, and other binary data, to a server.

Here is an example of how to create a new FormData object:

const formData = new FormData();

You can then add data to the FormData object using the append() method:

formData.append('name', 'John Doe');
formData.append('age', 30);
formData.append('file', fileInput.files[0]);

In this example, we are adding three pieces of data to the FormData object: a string value for the name key, an integer value for the age key, and a file object for the file key.

You can also add multiple files to the FormData object:

const files = document.getElementById('fileInput').files;
for (let i = 0; i < files.length; i++) {
  formData.append('files', files[i]);
}

Once you have added all the data you want to send, you can send the FormData object to a server using the XMLHttpRequest object or the fetch API:

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/upload', true);
xhr.send(formData);

Or using the fetch API:

fetch('https://example.com/upload', {
  method: 'POST',
  body: formData,
})

Note that when sending a FormData object to a server, the data is sent as a multipart/form-data request, which allows you to send both text and binary data in a single request.

Here is an example of what the request might look like:

POST /upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=---------------------------1234567890

-----------------------------1234567890
Content-Disposition: form-data; name="name"
Content-Type: text/plain

John Doe
-----------------------------1234567890
Content-Disposition: form-data; name="age"
Content-Type: text/plain

30
-----------------------------1234567890
Content-Disposition: form-data; name="file"; filename="example.txt"
Content-Type: text/plain

[file contents]
-----------------------------1234567890--

In this example, the request includes three form fields: name, age, and file. The file field contains the contents of a file named example.txt.