Method of Uploading Files and Pictures with FormData in JS

  • 2021-07-09 07:06:30
  • OfStack

About FormData

XMLHttpRequest Level 2 adds a new interface--FormData

Using FormData object, we can use js to simulate 1 series form control with 1 key value pair, and we can use send () method of XMLHttpRequest to submit form asynchronously. Compared with common ajax, the biggest advantage of using FormData is that we can upload binary file asynchronously

FormData Object

FormData object, can all form elements of name and value into an queryString, submitted to the background. When committing using ajax, using FormData objects can reduce the workload of splicing queryString

queryString is the query string, http query string from url? The following values specify

When form on the page sends the requested data to the page in GET mode (if the data contains unsafe characters, the browser first converts it into hexadecimal characters and then transmits it, if the space is converted to% 20), web server puts the requested data into an environment variable named QUERY_STRING. The Request. QueryString method takes the corresponding value from this 1 environment variable and restores the characters converted to hexadecimal
Upload files and pictures using FormData

Create an FormData empty object and add key/value using the append method


var formdata=new FormData();
 formdata.append ("name" , " Zhang 3");

If there is already one Form form, get the form object and pass it into the FormData object as a parameter


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <title></title>
</head>
<body>
  <form name="form1" id="form1">
    <input id="file" type="file" name="name"></input>
  </form>
  <script type="text/javascript">
     var form=document.getElementById("form1");
     var formdata=new FormData(form);
  </script>
</body>
</html> 

You can continue to add new key-value pairs based on existing form data


var formdata=new FormData();
 formdata.append ("age" , "21");

Upload files using FormData objects


var formdata=new FormData($("#form1").[0]);// Obtaining file method 1
//var formdata=new FormData( ); 
//formdata.append("file" , $("#file")[0].files[0]);// Obtaining file method 2
       $.ajax({
           type : 'post',
           url : '#',
           data : formdata,
           cache : false,
           processData : false, //  The sent data is not processed because data Value is Formdata Object, you do not need to process the data 
           contentType : false, //  Do not set Content-type Request header 
           success : function(){}
           error : function(){ }
       })

The above is the site to introduce to you JS using FormData upload files, pictures of the full description of the method, I hope to help you, if you have any questions welcome to give me a message!


Related articles: