Use of HTML5 Form Data Objects

Use of HTML5 Form Data Objects

  [  Reprinted from Dream Sky 's Blog] :  https://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html
  XMLHttpRequest Level 2 adds a new interface - FormData. Using the FormData object, we can simulate a series of form controls with some key-value pairs through JavaScript, and we can also use XMLHttpRequest's send() method 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);


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

  In this example, we create a FormData object named oMyForm that contains field names named "username", "accountnum", "userfile" and "webmasterfile", and then use XMLHttpRequest's send() method These data are sent out. The value of the "webmasterfile" field is not a string, but a Blob object.

Use an HTML form to initialize a FormData object

A FormData object can be initialized with an existing form element by passing the form element as a parameter to the FormData constructor:

var newFormData = new FormData(someFormElement);


  E.g:

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


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

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


  This way you can add some fixed fields that you don't want the user to edit before sending.

Send file using FormData object

You can also use FormData to send binary files. First you have a form element in the HTML that contains the 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>
<div id="output"></div>
<a href="javascript:sendForm()">Stash the file!</a>


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


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

data.append("myfile", myBlob);


  If a field value in the FormData object is a Blob object, when sending an HTTP request, the value of the "Content-Disposition" request header representing the file name of the file contained in the Blob object is different under different browsers , Firefox uses a fixed string "blob", 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请求头
});

Browser Compatibility

  Desktop side:

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 7+ 4.0 (2.0) 10+ 12+ 5+
Support filenameparameters (Yes) 22.0 (22.0) ? ? ?

  Mobile: 

Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 3.0 ? 4.0 (2.0) ?

12+

?
Support filenameparameters ? ? 22.0 (22.0) ? ? ?

references:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325485396&siteId=291194637