Home >Web Front-end >JS Tutorial >How to Perform jQuery Ajax File Uploads Without Plugins?

How to Perform jQuery Ajax File Uploads Without Plugins?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 17:05:17510browse

How to Perform jQuery Ajax File Uploads Without Plugins?

jQuery Ajax File Upload Without Using a Plugin

File upload using jQuery's AJAX requires the use of XHR2, supported by modern browsers. If you want to perform file upload using AJAX without a plugin, you need to use theFormDataobject.

Code:

 var formData = new FormData();
 formData.append("file", file); // Replace "file" with your file input element's name

$.ajax({
    type: "POST",
    timeout: 50000,
    url: url,
    data: formData,
    contentType: false,
    processData: false, // Don't process the form data, leave it as pure binary data
    success: function (data) {
        alert('success');
        return false;
    }
});

Notes:

  • FormData object can also contain other data, such as text input fields.
  • contentType and processData options are set to false to prevent jQuery from automatically converting the data as part of the AJAX request.
  • You must include the file name in the formData object using the name attribute of the file input element.
  • AJAX file upload may not be supported by all browsers. Check browser compatibility.

The above is the detailed content of How to Perform jQuery Ajax File Uploads Without Plugins?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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