Formdata object for AJAX requests, uploading files

Source: Internet
Author: User
This article for everyone to share the content is Formdata object Ajax request and upload the file method, the need for friends can refer to.

XMLHttpRequest Level2 added a new interface--formdata . " is primarily used to send form data, but it can also be used to transfer keying data independently. It can asynchronously upload binary files compared to normal Ajax . "

Using the Formdata object, you can use JS to simulate a series of form controls with some key-value pairs, and you can submit the form asynchronously using the XMLHttpRequest Send () method.

First of all, in the previous "forward and backward interaction of the method of communication" in the traditional form of form submission (form serialization), it only applies to pass general parameters, the file stream of the uploaded file cannot be serialized and passed. So, with Formdata, it's easy to upload files with Ajax.

First, before introducing the AJAX request using Formdata and uploading the file, come to know the Formdata and its use::::

The draft project provides three ways to obtain or modify Form Data::

WAY1: Create an empty Form Data object, and then add the key value pair individually with append ()

var omyform = new FormData ();    Create an empty Formdata object Omyform.append ("UserName", "Coco");       Append () method Add Field Omyform.append ("AccountNum", 123456);   The number 123456 is immediately converted to the string "123456" Omyform.append ("UserFile", fileinputelement.files[0]); var ofilebody = "<a id=" a "> <b id= "B" >hey!</b></a> "var oblob = new Blob ([Ofilebody],{type:" text/html "});  The Blob object contains the contents of the file Ofilebodyomyform.append ("Webmasterfile", Oblob), var oreq = new XMLHttpRequest (); Oreq.open ("POST", "   . php "); Opeq.send (omyform);   Send data using XMLHttpRequest's Send ()

The values of "UserFile" and "Webmasterfile" above contain a file;

The value of a field can be a Blob object, a file object or a string, and other types are automatically converted to strings-for example, "AccountNum" above.

WAY2: Takes the form element object as a parameter into the Formdata object

--Pseudo code--

var new_formdata = new FormData (someformelement);

Cases:

var formelement = document.getElementById ("Myformelement"), var oreq = new XMLHttpRequest (); Oreq.open ("POST", "     . PHP "); Oreq.send (new FormData (FormData));

You can also continue to add new key-value pairs based on existing forms:

var formelement = document.getElementById ("Myformelement"), var formData = new FormData (formelement); Formdata.append (" SerialNumber ", serialnumber++); var oreq = new XMLHttpRequest (); Oreq.send (FormData);

In this way, you can add some fixed fields that you do not want the user to edit, and then send them.

WAY3: Using the Getformdata method of the Form object to generate

var formobj = document.getElementById ("myformelement"); var formdata = Formobj.getformdata ();

Using FormData object, combined with native JS, asynchronously uploads images via Ajax. Of course, the existing jquery batch upload plugin, the principle is to use FormData.

Second, send binary files using Formdata object::::::

Way1: Initialize FormData with form forms

1. There is a FORM element in HTML that contains a file input box

<form enctype= "Multipare/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= "/><br>"      <label>custom file label:</label>      <input type= "text" Name= " Filelabel "  size=" maxlength= "/><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>

2, asynchronously upload the user selected files

function Sendform () {      var ooutput = document.getElementById ("Output");      var oData = new FormData (Document.forms.nameItem ("FileInfo"));      Odata.append ("CustomField", "This is some extra data");            var oreq = new XMLHttpRequest ();      Oreq.open ("POST", "     . php", true);      Oreq.onload = function (oevent) {                  if (oreq.status = =) {                   ooutput.innerhtml = "uploaded!";            } else{                   ooutput.innerhtml = "Error" + oreq.status + "occurred uploading your file!"            }      };      Oreq.send (oData);}

WAY2: Add a File object or a Blob object directly to the FormData object without using the form form

var data = new FormData (), var ofilebody = "<a id=" a "><b id=" B ">hey!</b></a>"; var oblob = new Blob ( [Ofilebody],{type: "Text/html"});d Ata.append ("MyFile", Oblob);

If a field value in the FormData object is a Blob object, the value of the "content-disposition" request that represents the file name of the files contained in the Blob object is different in different browsers when the HTTP request is sent:

Firefox uses a fixed string "blob", while Chrome uses a random string.

WAY3: Send FormData with Jquery (to set related items correctly)

var fd =new FormData (document.getElementById ("FileInfo")), Fd.append ("CustomField", "This is some extra data"), $.ajax ({     URL: "    . php",     Type: "POST",     data:fd,     processdata:false,   //  tell jquery not to process the sent data     Contenttype:false    //Tell jquery not to set Content-type request header});

Iii. examples

1. Use Fromdata for Ajax requests and upload files

<form id= "Uploadform" >      Specify File name: <input type= "text" name= "filename" value= "" >      Upload file: <input type= " File "name=" file ">             <input type=" button "value=" Upload "onclick=" doupload () "></form>
function Doupload () {    var formData = new FormData ($ ("#uploadForm") [0]);    $.ajax ({          URL: "   . php",          Type: "POST",          data:formdata,          async:false,          cache:false          , Contenttype:false,          Processdata:false,          success:function (returndata) {                 alert (returndata);          },          error:function (returndata) {                 alert ("Error:" +returndata);}}    );

2. Use FormData to submit the form and upload the image

<form name= "form" id= "FormData" > Name:<input type= "text" name= "name" &       Gt Gender:<input type= "Radio" name= "Gender" value= "1" > Male <input type= "Radio" name= "Gender" va Lue= "2" > Female photo:<input type= "file" name= "photo" id= "photo" > <input type= "button" Name= "BTN" Value= "Submit" onclick= "submit ();" > </form><p id= "result" ></P> 
function submit () {var data = new FormData ($ ("#formData") [0]);              $.ajax ({url: ". php", type: "POST", Data:data, DataType: "JSON",                          Cache:false, Processdata:false, Contenttype:false}). Done (function (ret) {                      if (ret["issuccess"]) {var result = "";                      Result + = "name=" + ret["name" + "<br>";                      Result + = "gender=" + ret["gender" + "<br>";                                                   Result + = "

Iv. Browser compatibility

Chrome Firefox (Gecko) Ie Opera Safari
7+ 4.0 (2.0) + + 12+ 5+

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.