Tutorial for uploading files without refresh using PHP and HTML5 FormData

  • 2021-07-18 07:23:22
  • OfStack

Uploading files without refresh is a common and somewhat complicated problem, and the common solution is to construct iframe.

An FormData object API is provided in HTML5, and a form request can be easily constructed through FormData and sent through XMLHttpRequest. It is also possible to send files through FormData objects, so uploading without refresh becomes very simple.

So how to use FormData? The following site gives a brief introduction to this.

1. Construct an FormData object

To get an FormData object, it is very simple:


var fd = new FormData();

The FormData object provides only one method, append, for adding form request parameters to the object.
In current mainstream browsers, FormData can be obtained or modified in the following two ways.
Method 1: Create an empty FormData object, and then add key-value pairs one by one using the append method. Example:


var fd = new FormData();
fd.append("name", " Script House ");
fd.append("blog", "http://ofstack.com");
fd.append("file", document.getElementById("file"));

This method eliminates the need for the form object of HTML.
Method 2: Get the form element object and pass it as a parameter into the FormData object. Example:


var formobj = document.getElementById("form");
var fd = new FormData(formobj);

Of course, you can continue to add other parameters to fd using the append method.

2. FormData Send Request

Got the FormData object, how to send the request? The FormData object is primarily used in the send method of the enhanced XMLHttpRequest object. Refer to the following example:


var xhr = new XMLHttpRequest();    
xhr.open("POST" ,"http://ofstack.com" , true);
xhr.send(fd);
xhr.onload = function(e) {
  if (this.status == 200) {
    alert(this.responseText);
  }
};

3. Using FormData in jquery

In the ajax method of jQuery, FormData can also be used to upload without refresh. However, pay attention to the setting of parameters, refer to the following:


$.ajax({
  url: "http://ofstack.com",
  type: 'POST',
  data: fd,
  /**
   * Must false Will automatically add the correct Content-Type
   */
  contentType:false,
  /**
   *  Must false Will avoid jQuery Right  formdata  Default processing of 
   * XMLHttpRequest Will be right  formdata  Carry out correct treatment 
   */
  processData:false
}).done(function(result){
  console.log(result);
}).fail(function(err){
  console.log(err);
});

4. 1 complete example (including PHP processing example):


<?php
//php  Receive form submission information and print it 
if( isset( $_REQUEST['do']) ){
  var_dump($_REQUEST);
  var_dump($_FILES);
  die();
}

?>
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>FormData Test - ofstack.com</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  </head>
  <body>
    <form id="form">
      <input type="file" name="file" id="file" />
      <input type="text" name="name" id="" value=" Script House " />
      <input type="text" name="blog" id="" value="http://ofstack.com" />
      <input type="submit" name="do" id="do" value="submit" />
    </form>
    <script>
    $("form").submit(function(e){
      e.preventDefault();
      
      // Empty object and add 
      var fd = new FormData();
      fd.append("name", " Script House ");
      fd.append("blog", "http://ofstack.com");
      fd.append("file", document.getElementById("file"));
      //fd.append("file", $(":file")[0].files[0]); //jQuery  Mode 
      fd.append("do", "submit");
      
      // Create from a form object  FormData
      var fd = new FormData(document.getElementById("form"));
      //var fd = new FormData($("form:eq(0)")[0]); //jquery  Mode 
      
      //XMLHttpRequest  Send a request in a native way 
      var xhr = new XMLHttpRequest();    
      xhr.open("POST" ,"" , true);
      xhr.send(fd);
      xhr.onload = function(e) {
        if (this.status == 200) {
          alert(this.responseText);
        };
      };
      return;
      //jQuery  Send the request in the mode 
      $.ajax({
        type:"post",
        //url:"",
        data: fd,
        processData: false,
        contentType: false
      }).done(function(res){
        console.log(res);
      });
      
      return false;
    });
    </script>
  </body>
</html>


Related articles: