Home > Web Front-end > H5 Tutorial > Example of how to upload files using jQuery HTML5 and FormData

Example of how to upload files using jQuery HTML5 and FormData

不言
Release: 2018-11-06 14:23:49
Original
2865 people have browsed it

Before HTML5, there were a series of jQuery technologies and plug-ins to implement AJAX file upload. HTML5 introduces the FormData class that simplifies file uploading. This article will introduce you to an example of how to upload files using jQuery HTML5 and FormData.

$('#myform').on('sumbit', function(){
    var form = $(this);
    var formdata = false;
    if (window.FormData)
    {
        formdata = new FormData(form[0]);
    }
    var formAction = form.attr('action');
    $.ajax({
        url         : '/upload',
        data        : formdata ? formdata : form.serialize(),
        cache       : false,
        contentType : false,
        processData : false,
        type        : 'POST',
        success     : function(data, textStatus, jqXHR){
            // Callback code
        }
    });
    });
Copy after login

You don’t need any plug-ins, flash or iframe skills to achieve this effectively. Here are some tricks to make this code work the way we expect:

When we create an instance of FormData, we pass form[0] instead of form. It means actual form elements, but not jQuery selectors.

We just pass false instead of defining contentType. This means that jQuery does not add the Content-Type header to the request.

We set processData to false, so jQuery will not convert our data value (based on FormData) to a string.

The above is the detailed content of Example of how to upload files using jQuery HTML5 and FormData. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template