Home > Article > Web Front-end > Example of how to upload files using jQuery HTML5 and FormData
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 } }); });
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!