Home > Web Front-end > JS Tutorial > How to Use AJAX and FormData for File Uploads?

How to Use AJAX and FormData for File Uploads?

Susan Sarandon
Release: 2024-12-16 08:45:10
Original
682 people have browsed it

How to Use AJAX and FormData for File Uploads?

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:

  • Supply the entire form for processing:
var form = $('form')[0];
var formData = new FormData(form);
Copy after login
  • Specify exact data for FormData:
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Copy after login

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
});
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template