πŸ§ͺ AJAX Form and File Handling
Estimated reading: 4 minutes 279 views

AJAX – File Uploading Techniques: A Complete Developer’s Guide


Introduction – Why Upload Files Using AJAX?

Traditionally, uploading files through HTML forms results in a full-page refresh, which is disruptive and inefficient. With AJAX file uploading, users can upload files asynchronouslyβ€”without page reloadsβ€”while receiving progress feedback, preview images, and dynamic error messages.

AJAX file uploads are essential for:

  • Profile image uploads
  • Resume/CV attachments
  • Image galleries
  • Drag-and-drop upload interfaces

In this guide, you’ll learn:

  • How to upload files with AJAX using FormData
  • Implementations using XMLHttpRequest and fetch()
  • How to show upload progress and preview
  • Server-side (PHP) file handling tips

Basic File Input HTML Structure

<form id="uploadForm">
  <input type="file" id="fileInput" name="uploadFile" />
  <button type="submit">Upload</button>
</form>
<div id="uploadStatus"></div>

File Upload Using AJAX with FormData and XMLHttpRequest

JavaScript (XHR Method)

document.getElementById("uploadForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const file = document.getElementById("fileInput").files[0];
  const formData = new FormData();
  formData.append("uploadFile", file);

  const xhr = new XMLHttpRequest();
  xhr.open("POST", "upload.php", true);

  xhr.onload = function () {
    if (xhr.status === 200) {
      document.getElementById("uploadStatus").innerText = xhr.responseText;
    } else {
      document.getElementById("uploadStatus").innerText = "Upload failed.";
    }
  };

  xhr.send(formData);
});

Best for legacy browser support or when needing granular control.


File Upload Using fetch() and FormData

document.getElementById("uploadForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const formData = new FormData(this);

  fetch("upload.php", {
    method: "POST",
    body: formData
  })
    .then(res => res.text())
    .then(result => {
      document.getElementById("uploadStatus").innerText = result;
    })
    .catch(() => {
      document.getElementById("uploadStatus").innerText = "Error during upload.";
    });
});

Cleaner syntax. No need to set headers manuallyβ€”fetch detects FormData and handles it.


Show Upload Progress with XMLHttpRequest

xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    const percentComplete = Math.round((event.loaded / event.total) * 100);
    document.getElementById("uploadStatus").innerText = `Uploading: ${percentComplete}%`;
  }
};

Gives real-time feedback to the user during file uploads.


Preview Image Before Upload

document.getElementById("fileInput").addEventListener("change", function () {
  const file = this.files[0];
  const reader = new FileReader();

  reader.onload = function (e) {
    const img = document.createElement("img");
    img.src = e.target.result;
    img.width = 150;
    document.getElementById("uploadStatus").innerHTML = "";
    document.getElementById("uploadStatus").appendChild(img);
  };

  reader.readAsDataURL(file);
});

Enhances UX by allowing users to preview images before upload.


Server-Side PHP Code (upload.php)

<?php
if ($_FILES['uploadFile']) {
  $targetDir = "uploads/";
  $fileName = basename($_FILES["uploadFile"]["name"]);
  $targetFile = $targetDir . $fileName;

  if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $targetFile)) {
    echo "Upload successful: " . $fileName;
  } else {
    echo "Upload failed.";
  }
} else {
  echo "No file received.";
}
?>

Make sure the uploads/ folder is writable and secure.


Security Best Practices

Risk Mitigation
File overwriteRename uploaded files uniquely
Malicious file typesValidate MIME type and extension
Large file sizesSet max file size limits (PHP & JS)
Unauthorized accessRestrict folder access via .htaccess
Server overloadUse asynchronous queues for large files

Common Mistakes to Avoid

Mistake Fix
Forgetting e.preventDefault()Prevent page reload on form submission
Manually setting headers for FormDataLet browser set Content-Type
Not checking file typeValidate using MIME or extension
Uploading huge files without limitsSet limits on both client and server sides

Summary – Recap & Takeaways

AJAX makes file uploading seamless, interactive, and dynamic. Whether you’re using XMLHttpRequest or the modern fetch() API, you can build fast and user-friendly file upload systems that enhance user experience and improve performance.

Key Takeaways:

  • Use FormData to handle file input easily
  • XMLHttpRequest supports progress tracking with .upload.onprogress
  • fetch() provides cleaner syntax for modern projects
  • Always validate file type, size, and server-side security

Next Steps:

  • Add drag-and-drop support using DragEvent API
  • Build multi-file upload with preview and validation
  • Integrate file uploads with cloud storage (AWS S3, Firebase)

FAQs – AJAX File Uploading


Can I upload multiple files using AJAX?
Yes. Use multiple in the <input> and loop through files:

for (const file of input.files) {
  formData.append("files[]", file);
}

How can I show real-time upload progress?
Use the xhr.upload.onprogress event for progress percentages.


Is it safe to upload files via AJAX?
It’s safe if you validate file size, MIME type, and filename on the server.


Why shouldn’t I set headers manually for FormData?
The browser automatically adds the correct multipart boundaries.


Can I upload files using JSON?
No. File objects must be sent as Blob or through FormData, not JSON.


Share Now :
Share

AJAX – File Uploading Techniques

Or Copy Link

CONTENTS
Scroll to Top