Use of FormData object, use of FormData object

Source: Internet
Author: User

Use of FormData object, use of FormData object
Use of FormData objects in this article

  1. How to Create a FormData object
  2. Create a FormData object using an HTML form
  3. Upload a file using the FormData object
  4. You can use AJAX to submit forms and upload files without using FormData objects.
  5. Related Links

The FormData object can be used to assemble a groupXMLHttpRequestThe key/value pair that sends the request. It can send form data more flexibly and conveniently, because it can be used independently of the form. If you set the form encoding type to multipart/form-datasubmit()The data format for method transmission is the same.

How to Create a FormData object Edit

You can create a FormData object by yourself, and then call itsappend()Add fields as follows:

Var formData = new FormData (); formData. append ("username", "Groucho"); formData. append ("accountnum", 123456); // The number 123456 is immediately converted to the string "123456" // input of the HTML file type. The user selects formData. append ("userfile", fileInputElement. files [0]); // JavaScript file-like object var content = '<a id = "a"> <B id = "B"> hey! </B> </a> '; // The text of the new file... var blob = new Blob ([content], {type: "text/xml"}); formData. append ("webmasterfile", blob); var request = new XMLHttpRequest (); request. open ("POST", "http://foo.com/submitform.php"); request. send (formData );
Note:The fields "userfile" and "webmasterfile" both contain a file. The field "accountnum" is a numeric type and will be FormData.append()Method to convert the string type ( FormDataThe field type of the object can be Blob, File, Or string: If its field type is neither Blob nor File, it will be converted to the string type.

The preceding example createsFormDataThe instance contains four fields: "username", "accountnum", "userfile", and "webmasterfile ".XMLHttpRequestOfsend()Method To send form data. The field "webmasterfile" isBlobType. OneBlobObject indicates an immutable file object similar to the original data. Blob data is not necessarily in a JavaScript native format.FileBased on Blob, the interface inherits the blob function and extends it to support files on the user system. You can useBlob()The constructor creates a Blob Object.

Create a FormData object Edit using an HTML form

To construct a FormData object containing Form data, you must specify the elements of the Form when creating the FormData object.

Var formData = new FormData (someFormElement); example: var formElement = document. querySelector ("form"); var request = new XMLHttpRequest (); request. open ("POST", "submitform. php "); request. send (new FormData (formElement ));

You can also attach additional data to the FormData object after creating a FormData object that contains Form data and before sending a request, as shown in the following code:

var formElement = document.querySelector("form");var formData = new FormData(formElement);var request = new XMLHttpRequest();request.open("POST", "submitform.php");formData.append("serialnumber", serialNumber++);request.send(formData);

In this way, you can freely add fields not necessarily edited by the user to the form data before sending the request.

Use the FormData object to upload the file Edit

You can also use FormData to upload files. You need to add a file type input to the form when using it:

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

Then use the following code to send the request:

var form = document.forms.namedItem("fileinfo");form.addEventListener('submit', function(ev) {  var oOutput = document.querySelector("div"),      oData = new FormData(form);  oData.append("CustomField", "This is some extra data");  var oReq = new XMLHttpRequest();  oReq.open("POST", "stash.php", true);  oReq.onload = function(oEvent) {    if (oReq.status == 200) {      oOutput.innerHTML = "Uploaded!";    } else {      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";    }  };  oReq.send(oData);  ev.preventDefault();}, false);

Note:If the FormData object is created through a form, the request method specified in the form will be applied to the open () method.

You can also directly attach a File or Blob type File to the FormData object, as shown below:

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

When using the appned () method, you can use the third optional parameter to set the request header.Content-Disposition Specifies the file name. If the file name is not specified (or this parameter is not supported), the name "blob" is used ".

If you set the correct configuration items, you can also use the FormData object using jQuery:

Var fd = new FormData (document. querySelector ("form"); fd. append ("CustomField", "This is some extra data"); $. ajax ({url: "stash. php ", type:" POST ", data: fd, processData: false, // do not process data contentType: false // do not set the content type });
You can use AJAX to submit forms and upload files without using FormData objects.

If you want to know that the FormData object is not used, click here to serialize and submit the form through AJAX.

Blob Object in-depth understanding, move here: https://developer.mozilla.org/zh-CN/docs/Web/API/Blob

This article is reproduced in mdn: https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.