Upload Ajax file with FormData

Tram Ho

1. What is FormData

FormData is a new interface introduced by HTML5 in the Web API.

Most of us have ever intercepted or edited data when submitting forms with Jquery. FormData is a Web API interface that provides a different approach to form handling. Using FormData is the same as using ajax jquery.

2. How to use the Data form

2.1. .append ()

Insert key-value pairs into the form data. Just like we insert hidden_field input into a regular form.

2.2 .delete ()

Delete the key-value pair in the FormData Object

2.3 Loop through key-values ​​with entries

We can loop through the key-values ​​of FormData with entries

2.4 .get ()

Get the first value of the formdata corresponding to the key

2.5 .getAll ()

Returns all values ​​of formdata corresponding to the key

2.6 .set ()

Assign a value to a corresponding key

3. Upload file with ajax formData

By default, the field file when submitting the form will not be added to ajax if we submit it normally. When submitting, fields [type = “file”] will be missing

With formData

By default, Ajax will set the processData option to true, automatically convert the data to a string, and set the content-type to “application / x-www-form-urlencoded”. False will skip this process and set the form’s default setting

ContentType: false also skip setting ajax’s default contentType to “application / x-www-form-urlencoded”.

4. Upload file with iframe

Another way to upload files is to use an iframe

Share the news now

Source : Viblo