Home > Web Front-end > H5 Tutorial > Detailed analysis of the use of HTML5 FormData object

Detailed analysis of the use of HTML5 FormData object

黄舟
Release: 2017-03-22 15:29:30
Original
1939 people have browsed it

 XMLHttpRequest Level 2 adds a new interface - FormData. Using the FormData object, we can use some key-value pairs to simulate a series of form controls through JavaScript. We can also use the send() method of XMLHttpRequest to submit the form asynchronously . Compared with ordinary Ajax, the biggest advantage of using FormData is that we can upload binary files asynchronously.

Create a FormData object

You can first create an empty FormData object, and then use the append() method to add fields to the object , as follows:

var oMyForm = new FormData();

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // 数字123456被立即转换成字符串"123456"

// fileInputElement中已经包含了用户所选择的文件
oMyForm.append("userfile", fileInputElement.files[0]);

var oFileBody = "<a id="a"><b id="b">hey!</b></a>"; // Blob对象包含的文件内容
var oBlob = new Blob([oFileBody], { type: "text/xml"});

oMyForm.append("webmasterfile", oBlob);

var oReq = new XMLHttpRequest();
oReq.open("POST", "http://foo.com/submitform.php");
oReq.send(oMyForm);
Copy after login

Note: The values ​​of the fields "userfile" and "webmasterfile" both contain a file. Numbers assigned to the field "accountnum" through the FormData.append() method are automatically converted into characters (the value of the field can be a Blob object, File object Or string, the rest of the other types of values ​​will be automatically converted into strings).

In this example, we create a FormData object named oMyForm, which contains field names named "username", "accountnum", "userfile" and "webmasterfile", and then use The send() method of XMLHttpRequest sends these data. The value of the "webmasterfile" field is not a string, but a Blob object.

Use HTML form to initialize a FormData object

You can use an existing form element to initialize the FormData object, just need to change this form Elements are passed in as parameters FormData Constructor Just like:

var newFormData = new FormData(someFormElement);
Copy after login

For example:

var formElement = document.getElementById("myFormElement");
var oReq = new XMLHttpRequest();
oReq.open("POST", "submitform.php");
oReq.send(new FormData(formElement));
Copy after login

You can also Based on the form data, continue to add new key-value pairs, as follows:

var formElement = document.getElementById("myFormElement");
formData = new FormData(formElement);
formData.append("serialnumber", serialNumber++);
oReq.send(formData);
Copy after login

You can add some fixed fields that you do not want users to edit in this way, and then send them.

Use the FormData object to send files

You can also use FormData to send binary files. First, there must be a form element in HTML that contains a file input box:

<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 />
</form>
<p id="output"></p>
<a href="javascript:sendForm()">Stash the file!</a>
Copy after login

Then you can use the following code to asynchronously upload the file selected by the user:

function sendForm() {
  var oOutput = document.getElementById("output");
  var oData = new FormData(document.forms.namedItem("fileinfo"));

  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 uploading your file.<br \/>";
    }
  };

  oReq.send(oData);
}
Copy after login

You can also add a File directly to the FormData object without using an HTML form Object or a Blob Object:

data.append("myfile", myBlob);
Copy after login

If a field value in the FormData object is a Blob object, when sending an HTTP request, it represents The Blob object contains the file name of the file . The value of the "Content-Disposition" request header is different in different browsers. Firefox uses The fixed string "blob" is used, while Chrome uses a random string.

You can also use jQuery to send FormData, but you must set the relevant options correctly:

var fd = new FormData(document.getElementById("fileinfo"));
fd.append("CustomField", "This is some extra data");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // 告诉jQuery不要去处理发送的数据
  contentType: false   // 告诉jQuery不要去设置Content-Type请求头
});
Copy after login

Browser compatibility

Desktop:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 7+ 4.0 (2.0) 10+ 12+ 5+
Support filenameparameter (Yes) 22.0 (22.0 ) ? ? ?
## Mobile version:

FeatureChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileBasic support3.0?4.0 (2.0 )??Support ??22.0 (22.0)???
Android
12+

filename parameter

The above is the detailed content of Detailed analysis of the use of HTML5 FormData object. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template