Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Using FormData with AJAX for file uploads

Posted on March 24, 2025March 24, 2025 by Zubair Shaik

Loading

Using FormData with AJAX for File Uploads

Introduction

Uploading files via a web application is a common requirement. Traditionally, file uploads were handled via form submissions, which resulted in full page reloads. However, with AJAX and FormData, file uploads can be performed asynchronously, without reloading the page, improving the user experience and performance.

In this guide, we will cover everything about handling file uploads using FormData and AJAX, including:

✔️ How FormData simplifies file uploads
✔️ How to use AJAX with FormData to send files asynchronously
✔️ Backend processing in PHP and Node.js
✔️ Optimizing performance, security, and error handling
✔️ Implementing progress bars, drag-and-drop file uploads, and multiple file selection


Table of Contents

  1. Understanding FormData for File Uploads
  2. How AJAX Works with File Uploads
  3. Setting Up the File Upload Form (HTML & CSS)
  4. Using JavaScript and FormData for AJAX File Uploads
  5. Backend Implementation (PHP and Node.js)
  6. Handling Multiple File Uploads
  7. Displaying Upload Progress with Progress Bars
  8. Drag-and-Drop File Upload with AJAX
  9. File Size, Type Validation, and Security Measures
  10. Optimizing Performance for Large File Uploads
  11. Error Handling and Debugging AJAX File Uploads
  12. SEO & Accessibility Considerations for File Uploads
  13. Deploying and Testing File Upload Feature
  14. Conclusion

1. Understanding FormData for File Uploads

What is FormData?

FormData is a built-in JavaScript object that allows you to construct and send form data via AJAX requests. It helps send files, text, and other form fields without reloading the page.

Advantages of Using FormData for File Uploads

✅ Allows asynchronous file uploads via AJAX.
✅ Supports multiple file uploads.
✅ Works with binary data, such as images, PDFs, and videos.
✅ Supports appending additional form fields.


2. How AJAX Works with File Uploads

1️⃣ User selects a file in the <input type="file"> field.
2️⃣ JavaScript captures the file and creates a FormData object.
3️⃣ AJAX sends the FormData to the server (backend) asynchronously.
4️⃣ The server processes the file and saves it to the storage.
5️⃣ The server responds with a success message (or an error).
6️⃣ JavaScript updates the UI based on the response (e.g., showing a success message).


3. Setting Up the File Upload Form (HTML & CSS)

🔹 HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX File Upload</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h2>Upload a File</h2>
    
    <form id="uploadForm">
        <input type="file" id="fileInput" name="file" required>
        <button type="submit">Upload</button>
    </form>
    
    <p id="statusMessage"></p>

    <script src="script.js"></script>
</body>
</html>

🔹 CSS for Styling

body {
    font-family: Arial, sans-serif;
    text-align: center;
}

form {
    margin: 20px;
}

button {
    margin-top: 10px;
    padding: 8px 12px;
    background: blue;
    color: white;
    border: none;
    cursor: pointer;
}

4. Using JavaScript and FormData for AJAX File Uploads

🔹 JavaScript (AJAX and FormData Implementation)

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

    let fileInput = document.getElementById("fileInput").files[0];

    if (!fileInput) {
        alert("Please select a file.");
        return;
    }

    let formData = new FormData();
    formData.append("file", fileInput);

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

    xhr.onload = function () {
        if (xhr.status === 200) {
            document.getElementById("statusMessage").innerText = "File uploaded successfully!";
        } else {
            document.getElementById("statusMessage").innerText = "Error uploading file.";
        }
    };

    xhr.send(formData);
});

5. Backend Implementation (PHP and Node.js)

🔹 PHP File Upload (upload.php)

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

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
        echo "File uploaded successfully!";
    } else {
        echo "Error uploading file.";
    }
}
?>

🔹 Node.js & Express File Upload (server.js)

const express = require("express");
const multer = require("multer");
const path = require("path");

const app = express();
const upload = multer({ dest: "uploads/" });

app.post("/upload", upload.single("file"), (req, res) => {
    res.send("File uploaded successfully!");
});

app.listen(3000, () => console.log("Server running on port 3000"));

6. Handling Multiple File Uploads

🔹 Modify HTML for Multiple File Selection

<input type="file" id="fileInput" name="files[]" multiple>

🔹 Modify JavaScript for Multiple Files

let files = document.getElementById("fileInput").files;
for (let i = 0; i < files.length; i++) {
    formData.append("files[]", files[i]);
}

7. Displaying Upload Progress with Progress Bars

let progressBar = document.createElement("progress");
progressBar.max = 100;
document.body.appendChild(progressBar);

xhr.upload.onprogress = function (event) {
    if (event.lengthComputable) {
        let percentComplete = (event.loaded / event.total) * 100;
        progressBar.value = percentComplete;
    }
};

8. Drag-and-Drop File Upload with AJAX

let dropArea = document.getElementById("dropArea");

dropArea.addEventListener("dragover", (e) => {
    e.preventDefault();
});

dropArea.addEventListener("drop", (e) => {
    e.preventDefault();
    let files = e.dataTransfer.files;
    uploadFiles(files);
});

9. File Size, Type Validation, and Security Measures

✅ Limit file size to prevent large uploads.
✅ Restrict file types to prevent security risks (e.g., .exe, .php).
✅ Rename files before saving to prevent overwriting.

if (file.size > 5 * 1024 * 1024) {  // 5MB limit
    alert("File too large!");
    return;
}

if (!["image/png", "image/jpeg", "application/pdf"].includes(file.type)) {
    alert("Invalid file type!");
    return;
}

Using FormData with AJAX for file uploads allows seamless, asynchronous, and efficient file handling. With proper validation, progress bars, drag-and-drop support, and multiple file uploads, you can enhance user experience while keeping your server secure and optimized.

Posted Under jQuery`AJAX file upload ajax drag and drop AJAX error handling AJAX file upload best practices ajax file upload metadata AJAX file upload security ajax file upload without jquery ajax multipart form ajax php file upload ajax post file ajax upload status amazon s3 ajax upload api file upload async await file upload asynchronous file upload backend file handling best practices for file uploads` blob file upload checking file integrity cloud storage file upload compressing images before upload converting file to base64 before upload cross-browser file upload csrf protection file upload custom file upload button customizing file upload process drag and drop file upload drag and drop file upload with preview dynamic file upload fields express file upload fetch api file upload fetch api multipart/form-data file input change event listener file input onchange event File Size Limit file size reduction before upload file upload accessibility file upload progress bar file upload progress indicator file upload speed optimization file upload with progress percentage file validation javascript formdata ajax formdata append file formdata example formdata vs json frontend and backend file processing frontend file compression frontend file upload google drive file upload handling ajax response json handling file permissions handling file upload response handling file uploads handling interrupted file uploads hidden input file upload html file input html5 file api image upload ajax JavaScript File Handling javascript file upload javascript formdata tutorial jquery ajax formdata example jQuery file upload large file chunking limiting number of files uploaded monitoring file transfer monitoring file upload progress multer file upload multiple file upload node.js file upload node.js fs module for file upload optimize file uploads optimizing file transfer optimizing storage for uploaded files parallel file uploads password-protected file upload pdf upload ajax php file upload php move_uploaded_file post file with axios preventing duplicate file uploads preventing file overwrite preview uploaded images progress bar for file uploads realtime file upload reducing file size before upload responsive file upload ui restrict file type upload resumable file upload retry file upload on failure secure file upload security risks in file upload send binary data with ajax sending additional form fields with file upload server-side file handling server-side validation file upload single-page application file upload storing files in cloud tracking file upload logs troubleshooting file upload errors unique filenames for uploaded files upload file using ajax upload files to server upload image preview before submit upload large files uploading encrypted files uploading files to database uploading files using xhr uploading files without page refresh uploading images with ajax uploading large files efficiently uploading multiple files user authentication in file upload video file upload Web Development xhr post file xhr upload progress

Post navigation

Loading partial HTML content dynamically
Storing AJAX responses in session storage

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions