AJAX File Upload with FormData
In the context of dynamic HTML, you've generated a file upload form via drag-and-drop and have JavaScript code for submitting the form using AJAX. However, to facilitate file upload using FormData, you need adjustments.
Preparations
To utilize FormData, choose one of the following:
var form = $('form')[0]; var formData = new FormData(form);
var formData = new FormData(); formData.append('section', 'general'); formData.append('action', 'previewImg'); // Attach file formData.append('image', $('input[type=file]')[0].files[0]);
Sending the Form
Use the provided jQuery snippet:
$.ajax({ url: 'Your url here', data: formData, type: 'POST', contentType: false, processData: false, // ... Other options like success and etc });
This request will mimic a regular form submission with enctype="multipart/form-data", allowing you to upload files successfully.
Note: Remember to specify type: "POST" in the options, as file uploads require POST requests.
Update: Starting with jQuery 1.6, contentType: false is supported.
The above is the detailed content of How to Use AJAX and FormData for File Uploads?. For more information, please follow other related articles on the PHP Chinese website!