Uploading files via Ajax, using Formdata for AJAX requests

Source: Internet
Author: User
upload a file by using a traditional form form submission:

<form id= "Uploadform" action= "Http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype = "multipart /form-data ">  
     


However, the traditional form form submission will cause the page to refresh, but in some cases we do not want the page to be refreshed, which is the way we use Ajax to make the request.


Ajax Way to make the request:

$.ajax ({  
     URL: "Http://localhost:8080/STS/rest/user",  
     Type: "POST",  
     Data: $ (' #postForm '). Serialize (),  
     success:function (data) {  
          $ (' #serverResponse '). HTML (data);  
     },  
     error:function (data) {  
          $ (' # Serverresponse '). HTML (data.status + ":" + Data.statustext + ":" + Data.responsetext);  
     }  

Usually when we submit (using the Submit button), the name and value of all the table elements in the form are made into a querystring and submitted to the background. In the way of jquery, this is serialize.

Through $ (' #postForm '). Serialize () Can serialize the form form to pass all parameters in the form form to the service side. However, the above method can only pass the general parameters, the file stream of the uploaded file cannot be serialized and passed. But now the mainstream browser is starting to support a object called Formdata, with this formdata, we can easily use the Ajax way to upload files.

about Formdata and its usage What is Formdata? Let's take a look at the introduction on Mozilla.

XMLHttpRequest Level 2 Adds a new interface FormData. Using the FormData object, we can simulate a series of form controls using JavaScript with some key-value pairs, and we can also use XMLHttpRequest's send    () method to commit the "form" asynchronously. The biggest advantage of using formdata is that we can upload a binary file asynchronously, rather than the usual Ajax.   This object has been supported by newer versions of all major browsers, such as Chrome 7+, Firefox 4+, IE + +, Opera 12+, Safari 5+. See also: Https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormData


Constructor


FormData ()


Want a Formdata object:

var formdata = new Formdata ();

The draft project provides three options for acquiring or modifying Formdata.


Scenario 1: Create an empty Formdata object, and then add the key-value pairs individually by using the Append method:

var formdata = new Formdata ();
Formdata.append ("name", "hehe");
Formdata.append ("url", "http://www.baidu.com/");

Scenario 2: Get the Form element object and pass it as a parameter into the Formdata object.

var formobj = document.getElementById ("form");
var formdata = new Formdata (formobj);

Scenario 3: Use the Getformdata method of the form element object to generate it.

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

Method Formdata.append

This method is used to add a new value to a key that already exists, such as if the key does not exist and is new. Grammar

Formdata.append (name, value);
Formdata.append (name, value, filename);
Note: The value assigned to the field through the Formdata.append () method if the number is automatically converted to a character (the value of the field can be a Blob object, a file object, or a string, the remaining types of values will be automatically converted to strings). parameter InterpretationName
Keys (key), corresponding form field value
Value of form field filename (optional)
The filename reported to the server (a usvstring) if a Blob or File is passed as the second parameter. The default filename for Blob, objects is "blob". Formdata.delete

Removes a pair of keys and values from the FormData object.

Formdata.delete (username);
Formdata.get

Returns the first value of a given key

Formdata.append (' username ', ' Justin ');
Formdata.append (' username ', ' Chris ');
Formdata.get (username);    "Justin"
Formdata.getall

Returns all values for the given key

Formdata.append (' username ', ' Justin ');
Formdata.append (' username ', ' Chris ');
Formdata.getall (username);    ["Justin", "Chris"]
Formdata.has

Checks whether the given key is included, returns TRUE or False

Formdata.has (username);
Formdata.set

Sets the value of the given key

Formdata.set (name, value);
Formdata.set (name, value, filename);
Browser compatibility Scenarios

From MDN:

Desktop

Feature Chrome Firfox (Gecko) intenet Explorer Opera Safari
Basic Support 7+ 4.0 (2.0) + 12+ 5+
Append with filename (Yes) 22.0 (22.0) ? ? ?
Delete, get, GetAll, has, set Behind Flag Not supported Not supported (Yes) Not supported

Mobile

Feature Android Chrome Android Firfox Mobile (Gecko) Firfox OS (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic Support 3.0 ? 4.0 (2.0) 1.0.1 ? 12+ ?
Append with filename ? ? 22.0 (22.0) 1.2 ? ? ?
Delete, get, GetAll, has, set (Yes) (Yes) Not supported Not supported Not supported (Yes) Not supported
Published on June 04, 2015


Ajax uploads files via Formdata



1. Uploading files using the <form> form initialization Formdata object method


HTML code

<form id= "Uploadform" enctype= "Multipart/form-data" >
    <input id= "file" type= "file" name= "file"/>
    <button id= "Upload" type= "button" >upload</button>
</form>


JavaScript code

$.ajax ({
    URL: '/upload ',
    type: ' POST ',
    cache:false,
    data:new FormData ($ (' #uploadForm ') [0]),
    Processdata:false,
    contenttype:false
}). Done (function (res) {
}). Fail (function (res) {});


Here are some points to note: ProcessData is set to false. Because the data value is a Formdata object, you do not need to do the processing. <form> tag Add enctype= "Multipart/form-data" property. The cache is set to False and the upload file does not need to be cached. ContentType is set to FALSE, the ContentType value is not set because it is a Formdata object constructed by the <form> form, and the attribute enctype= "Multipart/form-data" has been declared, So this is set to false.

After uploading, the server-side code needs to get the file input stream object from the query parameter named file, because name= "file" is declared in <input>.

What if you didn't construct the Formdata object with the <form> form?

2. Upload a file using the Formdata Object Add Field Method


HTML code

<
Related Article

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.