Home  >  Article  >  Backend Development  >  FormData object makes Ajax request and uploads files

FormData object makes Ajax request and uploads files

不言
不言Original
2018-07-18 16:20:233100browse

This article shares with you the method of making Ajax requests and uploading files using the FormData object. Friends in need can refer to it.

XMLHttpRequest Level2 adds a new interface - FormData. [ is mainly used to send form data, but can also be used independently to transmit keyed data. Compared with ordinary Ajax, it can upload binary files asynchronously

Using the FormData object, you can use some key-value pairs to simulate a series of form controls through js, and you can also Submit the form asynchronously using the send() method of XMLHttpRequest.

First of all, in the previous "Parameter Passing Method for Front-end and Back-end Interaction", we talked about the traditional form submission method (form serialization), which is only suitable for passing general parameters. The file stream of the uploaded file cannot be serialized and delivered. Therefore, using FormData, you can easily combine it with ajax to upload files.

1. Before introducing the use of FormData to make Ajax requests and upload files, let’s first get to know FormData and its use:::::

W3C draft provides three options to obtain or modify Form Data:::

WAY1: Create an empty Form Data object, and then use append() to add it one by one Key-value pair

var oMyForm = new FormData();    // 创建一个空的FormData对象
oMyForm.append("userName","Coco");       // append()方法添加字段
oMyForm.append("accountNum",123456);   // 数字123456立即被转换成字符串“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"});  // Blob对象包含的文件内容是oFileBody
oMyForm.append("webmasterfile",oBlob);
var oReq = new XMLHttpRequest();
oReq.open("POST","   .php");
oPeq.send(oMyForm);   // 使用XMLHttpRequest的send()把数据发送出去

The values ​​of "userFile" and "webmasterfile" above both contain a file; the

field The value can be a Blob object, File object or string. Other types will be automatically converted to strings - such as "accountNum" above.

WAY2: Take the form element object as a parameter and pass it into the FormData object

—— Pseudo code——

var new_FormData = new FormData( someFormElement );

Example:

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

You can also add new key-value pairs based on the existing form:

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

You can add some fixed fields that you don’t want users to edit in this way before sending.

WAY3: Use the getFormData method of the form object to generate

var formobj = document.getElementById("myFormElement");
var formdata = formobj.getFormData();

Use the FormData object, combined with native js, through Ajax implements asynchronous uploading of images. Of course, the principle of existing jquery batch upload plug-ins is to use FormData.

2. Use the FormData object to send binary files:::::

way1: Initialize FormData through the form form

1. There is a form element containing a file input box in html

616446c85450afc472a9bd8ec9e64146

      2e1cf0710519d5598b1f0f14c36ba674your email address:8c1ecd4bb896b2264e0711597d40766c
      77ea3818c28708bdfa2d740f63ca84430c6dc11e160d3b678d68754cc175188a

      2e1cf0710519d5598b1f0f14c36ba674custom file label:8c1ecd4bb896b2264e0711597d40766c
      c53720150e0e40fa90d71213512a19430c6dc11e160d3b678d68754cc175188a

      2e1cf0710519d5598b1f0f14c36ba674File to stash:8c1ecd4bb896b2264e0711597d40766c
      37618ecaa97ade89cdcd8c57e3705350f5a47148e367a6035fd7a2faa965022e8682d3dcb51d71511882c0fb08275db494b3e26ee717c64999d7867364b1b4a334fbcf1a3d1404e3f48634a414c8f9f7stash the file !5db79b134e9f6b82c0b36e0489ee08ed

2. Asynchronously upload the file selected by the user

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 == 200){
                   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"});

data.append("myfile",oBlob);

If a field value in the FormData object is a Blob object, when sending an HTTP request, the value of the "content-Disposition" request representing the file name of the file contained in the Blob object is different in different browsers:

Firefox uses the fixed string "blob", while chrome uses a random string.

WAY3: Use Jquery to send FormData (relevant items must be set 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,   //  告诉jquery不要处理发送的数据
     contentType:false    // 告诉jquery不要设置content-Type请求头});

3. Example

1. Use FromData to make Ajax requests and upload files

<form id="uploadForm">
      指定文件名:<input type="text" name="filename" value="">
      上传文件:<input type="file" name="file">
      
       <input type="button" value="上传" 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 forms and upload images

<form name="form" id="formData">

       name:<input type="text" name="name">
       gender:<input type="radio" name="gender" value="1"> male              
       <input type="radio" name="gender" value="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 += "<img src=&#39;"+ret[&#39;photo&#39;]+"&#39;width=&#39;100&#39;>";
                             
                      $("#result").html(result);         // 提交成功后将表单数据显示在id="result"的p里面     
                  }else{
                         alert("提交失败");
                   }
         });       return false;
}

4. Browser compatibility

Chrome Firefox(Gecko) IE Opera Safari
7 4.0(2.0) 10 12 5

Related recommendations:

jQuery uses FormData to implement file uploading

Use FormData to upload files with Ajax

The above is the detailed content of FormData object makes Ajax request and uploads files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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