How do you upload files asynchronously using jQuery AJAX and FormData? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
4 days ago

How do you upload files asynchronously using jQuery AJAX and FormData?

message-square
0

To upload files asynchronously in JavaScript using jQuery AJAX and FormData, collect the selected File objects (and any extra fields) into a FormData instance, pass it as data to $.ajax(), and set contentType: false and processData: false. Setting both flags to false prevents jQuery from converting the FormData payload into a URL-encoded query string or overriding the browser’s automatic multipart/form-data boundary header.


1. Uploading One or Multiple Files via FormData and $.ajax()

Build a FormData instance after validating the File objects (FileList / File checks, MIME type, and file size), then send it asynchronously with $.ajax() using contentType: false and processData: false:

// Upload files asynchronously via jQuery AJAX and FormData with input guards
function uploadFilesWithJQueryAjax(
  uploadUrl,
  files,
  extraFields = {},
  { maxBytes = 10 * 1024 * 1024, fieldName = "files" } = {}
) {
  if (typeof window.jQuery !== "function" || typeof uploadUrl !== "string" || uploadUrl.trim() === "") {
    return Promise.reject(new Error("jQuery and a valid upload URL are required."));
  }

  const fileList = Array.from(files || []);
  if (fileList.length === 0) {
    return Promise.reject(new Error("At least one file must be selected for upload."));
  }

  const formData = new FormData();

  for (const file of fileList) {
    if (!(file instanceof File) || file.size === 0 || file.size > maxBytes) {
      return Promise.reject(new Error(`Invalid or oversized file: ${file && file.name ? file.name : "unknown"}`));
    }
    formData.append(fieldName, file, file.name);
  }

  if (extraFields && typeof extraFields === "object") {
    for (const [key, value] of Object.entries(extraFields)) {
      if (value !== undefined && value !== null) {
        formData.append(key, String(value));
      }
    }
  }

  return new Promise((resolve, reject) => {
    window.jQuery.ajax({
      url: uploadUrl,
      method: "POST",
      data: formData,
      contentType: false,
      processData: false,
      success: (response) => resolve(response),
      error: (jqXHR, textStatus, errorThrown) => {
        reject(new Error(`Upload failed (${textStatus}): ${errorThrown || jqXHR.status}`));
      }
    });
  });
}

// Example usage with a file input element:
// const inputEl = document.getElementById("file-uploader");
// uploadFilesWithJQueryAjax("/api/uploads", inputEl.files, { category: "invoices" })
//   .then((res) => console.log("Uploaded:", res))
//   .catch((err) => console.error(err));
  • contentType: false: Lets the browser set Content-Type: multipart/form-data; boundary=... automatically.
  • processData: false: Stops jQuery from serializing FormData into application/x-www-form-urlencoded text.

2. Tracking Upload Progress via Custom xhr Hook in $.ajax()

When uploading larger files asynchronously, supply a custom xhr factory in $.ajax() to attach a progress listener on xhr.upload without mutating state outside the callback:

// Upload a file with jQuery AJAX while reporting upload progress percentage
function uploadFileWithProgress(uploadUrl, file, onProgress) {
  if (typeof window.jQuery !== "function" || !(file instanceof File)) {
    return Promise.reject(new Error("jQuery and a valid File instance are required."));
  }

  const formData = new FormData();
  formData.append("file", file, file.name);

  return new Promise((resolve, reject) => {
    window.jQuery.ajax({
      url: uploadUrl,
      method: "POST",
      data: formData,
      contentType: false,
      processData: false,
      xhr: () => {
        const xhr = window.jQuery.ajaxSettings.xhr();
        if (xhr && xhr.upload && typeof onProgress === "function") {
          xhr.upload.addEventListener("progress", (event) => {
            if (event.lengthComputable && event.total > 0) {
              const percent = Math.min(100, Math.round((event.loaded / event.total) * 100));
              onProgress(percent);
            }
          });
        }
        return xhr;
      },
      success: (data) => resolve(data),
      error: (jqXHR, status, err) => reject(new Error(err || `HTTP ${jqXHR.status} (${status})`))
    });
  });
}
  • Uses xhr.upload: Tracks bytes sent to the server rather than response download bytes.
  • Clamped percentage: Guards event.lengthComputable and event.total > 0 before computing progress.

3. Common Traps to Avoid

Uploading files with jQuery AJAX and FormData often runs into a few pitfalls:

  • Forgetting processData: false or contentType: false: Leaving either option at jQuery’s default breaks multipart file uploads with serialization errors or missing boundary headers.
  • Manually setting a hardcoded "Content-Type": "multipart/form-data" header: Hardcoding the header without the generated boundary string causes server multipart parsers to reject the request.
  • Relying solely on client-side file checks: Always enforce file size limits, allowed extensions/MIME types, and authentication/authorization on the server side.

TL;DR: Append files and fields to new FormData() and send it with $.ajax() using contentType: false and processData: false (plus an xhr.upload "progress" listener if you need progress percentages).