[Go] HTML5 FormData method Introduction and implement File upload

Source: Internet
Author: User

XMLHttpRequest is a browser interface through which we can make Javascript communicate in HTTP (S). XMLHttpRequest is now a common way to interact with data in front and back of the browser. In February 2008, XMLHttpRequest Level 2 was proposed, and it has some new features relative to the previous generation, where FormData is a newly added object in the XMLHttpRequest 2, which is used to submit forms, simulate form submissions, and, of course, the most The big advantage is that you can upload binary files. Here's how to use FormData to upload files.

FormData Uploading a file instance

First look at the basic usage of Formdata: Formdata object, you can put the name of all form elements and value of a querystring, submitted to the background. Just pass the form form as a parameter to the FormData constructor:

var form = document.getElementById("form1");var fd = new FormData(form);
    • 1
    • 2

This allows the FD to be sent to the background directly via the AJAX Send () method.

The following creates a form form that, in addition to normal data, has a file upload, and we directly pass the form object as a parameter to the Formdata object:

<FormName="Form1"Id="Form1" ><P>name:<InputType="Text"Name="Name"/></P><P>gender:<InputType="Radio"Name="Gender"Value="1"/>male<InputType="Radio"Name="Gender"Value="2"/>female</P><P>stu-number:<InputType="Text"Name="Number"/></P><P>photo:<InputType="File"Name="Photo"Id= "photo" ></p> <p>< Input type= "button" name=< Span class= "Hljs-value" > "B1" value= "submit" onclick=" Fsubmit () "/></ p> </form> <div id=  "result" ></DIV>   
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

The above code creates a form, simply fills in some information, and selects a picture as the Avatar, setting a div to hold the returned results.

For simplicity, we still use jquery encapsulated Ajax to transfer data to the background:

functionFsubmit() {var Form=document.getelementbyid ("Form1");var fd =New FormData (form); $.ajax ({URL:"Server.php", type:"POST", DATA:FD, ProcessData:FalseTell jquery not to handle the data sent ContentType:FalseTell jquery not to set Content-type request Header success:function (RESPONSE,STATUS,XHR) {Console.log (XHR); var Json=$.parsejson (response); var result =  "; result +=" personal information:< Br/>name: "+json[ ' name ']+ <br/>gender:" +json[ ' gender ']+ "<br/>number:" +json[ <br/> Avatar:  ' photo ' +  ' #result '). HTML (result);}}); return false;}        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st

The server.php in the code above is the server-side file that receives the AJAX request and returns the received result, with the following code:

<?php$name =Isset$_post[' name '])?$_post[' Name ']:‘‘;$gender =Isset$_post[' Gender '])?$_post[' Gender ']:‘‘;$number =Isset$_post[' Number ')?$_post[' Number ']:‘‘;$filename = Time (). substr ($_files[' Photo ' [' Name '], Strrpos ($_files[' Photo ' [' Name '],‘.‘));$response =Array ();if (Move_uploaded_file ($_files[' Photo ' [' Tmp_name '],$filename)) { $response [ ' issuccess '] = true; Span class= "hljs-variable" > $response [ ' name '] =  $name;  $response [ ' gender '] =  $gender;  $response [ ' number '] =  $number;  $response [ ' photo '] =  $filename; else{ $response [ ' isSuccess '] = Span class= "Hljs-keyword" >FALSE; } echo json_encode ( $response);                 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st

Fill in the good information, click Submit, the page can get the following effect, to the server side of the corresponding folder can also find uploaded images.

If you're a native JavaScript enthusiast, and of course you can do the same, here's the simple JavaScript implementation code:

functionFsubmit() {var Form=document.getelementbyid ("Form1");var formdata=New FormData (form); alert (formdata.name);var oreq =New XMLHttpRequest (); Oreq.onreadystatechange=function(){if (oreq.readystate==4) {if (oreq.status==() {Console.log (typeof Oreq.responsetext);var json=json.parse (oreq.responsetext); var result =  "personal information: <br/>name:" +json[ ' name ']+ "<br/>gender:" +json[  gender ']+ "<br/>number:" +json[  <br/> Avatar:  ' photo ' +  ' #result '). HTML (result);}} }; Oreq.open ( "POST",  "server.php"); Oreq.send (formData); return false;}         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
Introduction to FormData Object Methods

FormData In addition to the above to create a new object directly into the form as a parameter, there are other functions. Most of the online articles about FormData introduced only the Append () method, so what are the FormData objects? We'll know from the console:

After the console we have a major discovery, FormData object unexpectedly have such method, so still test to find the truth, the following on these methods are explained:

1, append ()

The append () method is used to add a key-value pair to the FormData object:

fd.append(‘key1‘,"value1");fd.append(‘key2‘,"value2");
    • 1
    • 2

FD is an FormData object that can create a new empty object, or it can be a form or other key-value pair that already contains a form.

2. Set ()

Sets the value corresponding to the key keys (s)

fd.set(‘key1‘,"value1");fd.set(‘key2‘,"value2");
    • 1
    • 2

It looks a bit like the Append () method, the difference between the two is that when the specified key value is present, the append () method is the addition of the added key-value pair last, and the set () method overwrites the previous set of key-value pairs. By contrast, we append () or set () new key-value pairs on the basis of the previous form:

fd.append(‘name‘,"will");
    • 1

There are two key-value pairs for name:

fd.set(‘name‘,"will");
    • 1

There is only one key value pair for name:

The above is the difference between append () and set (). If you set a key value that does not exist, the effect is the same.

3. Delete ()

Receive a parameter that indicates the name of the key value you want to delete, and if there are multiple identical key values, it will be deleted:

fd.append(‘name‘,‘will‘);fd.delete(‘name‘);
    • 1
    • 2

The name information in the form and the new name via append () are removed.

4, get () and GetAll ()

Receives a parameter that represents the name of the key that needs to be looked up, and returns the value of the first value corresponding to the key. If there are multiple identical keys, and you want to return all of the value values for this key.

This is also based on the form form above:

fd.append(‘name‘,‘will‘);console.log(fd.get(‘name‘)); // sean
    • 1
    • 2
fd.append(‘name‘,‘will‘);console.log(fd.getAll(‘name‘)); // ["sean", "will"]
    • 1
    • 2

5, has ()

The method also receives a parameter, which is also the name of the key, and returns a Boolean value that is used to determine whether the Formdata object contains the key. Take the form above as an example:

console.log(fd.has(‘name‘)); // trueconsole.log(fd.has(‘Name‘)); // false
    • 1
    • 2

6. Keys ()

The method does not need to receive parameters and returns an iterator through which we can traverse all the keys in the Formdata object. Take the form above as an example:

for (var key of fd.keys()) {           console.log(key);         }
    • 1
    • 2
    • 3

The result is:

namegendernumberphoto
    • 1
    • 2
    • 3
    • 4

7. VALUES ()

There are iterations that traverse key, and of course the iterator that iterates over the value. VALUES () is an iterator that iterates through value, using the same usage as keys ():

for (var value of fd.values()) {           console.log(value); }
    • 1
    • 2
    • 3

Results:

8, Entries ()

There is an iterator that iterates through a key, and an iterator that iterates over the value, why not make a combination of the two? Entries () is the return of an iterator containing a key-value pair:

for(var pair of fd.entries()) {           console.log(pair[0]+ ‘, ‘+ pair[1]); }
    • 1
    • 2
    • 3

Results:

formdata compatibility issues

Because FormData is the XMLHttpRequest Level 2 new interface, now less than IE10 IE browser does not support FormData, as described above, the method of FormData objects tested, in the IE browser is not supported, specific major browsing The support of the device can be referred to:

[Go] HTML5 FormData method Introduction and implement File upload

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.