HomeJavaScriptUpload multiple files - Fast, Secure, and Easy to Use

Upload multiple files – Fast, Secure, and Easy to Use

Here’s a complete solution for Upload multiple files with a progress bar using PHP, JavaScript (AJAX), and HTML. This approach includes the backend logic to handle multiple file uploads, and the frontend will display a progress bar for each file being uploaded.

Steps:

  1. PHP File: Handles multiple file uploads and returns a response.
  2. HTML & JavaScript: Displays the file upload form, tracks progress, and updates the progress bar for each file.
  3. CSS: Adds styling for the progress bar and the overall layout.

PHP File Handling for Multiple File Uploads: upload.php

<?php
$response = array();

if (!empty($_FILES['files']['name'][0])) {
    foreach ($_FILES['files']['name'] as $key => $name) {
        $targetDir = "uploads/";
        $targetFile = $targetDir . basename($name);
        
        // Check if the file was uploaded and there was no error
        if (move_uploaded_file($_FILES['files']['tmp_name'][$key], $targetFile)) {
            $response[] = array(
                "status" => "success",
                "fileName" => $name,
                "message" => "$name has been uploaded."
            );
        } else {
            $response[] = array(
                "status" => "error",
                "fileName" => $name,
                "message" => "Error uploading $name."
            );
        }
    }
} else {
    $response[] = array(
        "status" => "error",
        "message" => "No files were uploaded."
    );
}

echo json_encode($response);
?>

HTML & JavaScript for Multiple File Upload with Progress Bars: index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiple File Upload with Progress Bar</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #4db2ec;
            color: #333;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 100%;
        }
        .container form{
            height: 167px;
            display: flex;
            cursor: pointer;
            margin: 30px 0;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            border-radius: 5px;
            border: 2px dashed #6990F2;
        }

        h2 {
            text-align: center;
            color: #4db2ec;
        }

        input[type="file"] {
            display: block;
            margin: 10px auto;
            background: #4db2ec;
            color: #fff;
            padding: 15px;
        }

        .progress-wrapper {
            margin: 10px 0;
        }

        .progress-bar {
            width: 100%;
            background-color: #f3f3f3;
            border-radius: 5px;
            overflow: hidden;
        }

        .progress-bar-fill {
            height: 20px;
            width: 0;
            background-color: #4db2ec;
            transition: width 0.25s;
        }
        input[type="submit"] {
            background: #4db2ec;
            border: none;
            padding: 15px;
            color: #fff;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 20px;
        }
        .status {
            margin: 10px 0;
            font-size: 14px;
        }

        .success {
            color: #4CAF50;
        }

        .error {
            color: #f44336;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Multiple Files Uploader</h2>
    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="files[]" id="fileInput" multiple required>
        <input type="submit" value="Upload Files">
    </form>
    <div id="progressContainer"></div>
    <div id="messageContainer"></div>
</div>

<script>
    const uploadForm = document.getElementById('uploadForm');
    const fileInput = document.getElementById('fileInput');
    const progressContainer = document.getElementById('progressContainer');
    const messageContainer = document.getElementById('messageContainer');

    uploadForm.addEventListener('submit', function (e) {
        e.preventDefault();

        // Clear previous progress and messages
        progressContainer.innerHTML = '';
        messageContainer.innerHTML = '';

        const files = fileInput.files;
        const formData = new FormData();

        // Append all selected files to the formData
        for (let i = 0; i < files.length; i++) {
            formData.append('files[]', files[i]);
        }

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

        // Track the progress of the upload
        xhr.upload.addEventListener('progress', function (e) {
            if (e.lengthComputable) {
                const percentComplete = (e.loaded / e.total) * 100;
                updateProgressBar(percentComplete);
            }
        });

        // Handle the response from the server
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                response.forEach(res => {
                    const statusMessage = document.createElement('div');
                    statusMessage.className = `status ${res.status}`;
                    statusMessage.textContent = res.message;
                    messageContainer.appendChild(statusMessage);
                });
            }
        };

        // Send the form data
        xhr.send(formData);

        // Create progress bars for each file
        for (let i = 0; i < files.length; i++) {
            createProgressBar(files[i].name);
        }
    });

    function createProgressBar(fileName) {
        const progressWrapper = document.createElement('div');
        progressWrapper.className = 'progress-wrapper';

        const progressLabel = document.createElement('div');
        progressLabel.textContent = `Uploading ${fileName}...`;

        const progressBar = document.createElement('div');
        progressBar.className = 'progress-bar';

        const progressBarFill = document.createElement('div');
        progressBarFill.className = 'progress-bar-fill';
        progressBar.appendChild(progressBarFill);

        progressWrapper.appendChild(progressLabel);
        progressWrapper.appendChild(progressBar);
        progressContainer.appendChild(progressWrapper);
    }

    function updateProgressBar(percentComplete) {
        const progressBars = document.querySelectorAll('.progress-bar-fill');
        progressBars.forEach(bar => {
            bar.style.width = percentComplete + '%';
        });
    }
</script>

</body>
</html>

Explanation:

  1. PHP Backend (upload.php):
    • Handles the multiple file uploads.
    • Loops through all the files and attempts to move them to the uploads/ directory.
    • Returns a JSON response with the status of each file (success or error).
  2. HTML Frontend:
    • Contains a form that allows users to select multiple files.
    • Uses multipart/form-data to send the files to the server.
  3. JavaScript (AJAX and Progress Bars):
    • Prevents the form from being submitted traditionally (page reload).
    • Creates individual progress bars for each selected file.
    • Tracks the upload progress using the progress event and updates the progress bars.
    • Displays messages indicating the success or error status for each file after upload.
  4. CSS:
    • Adds styling for the progress bars, form, and messages.
    • Each file gets its own progress bar, and they are visually updated as the file is uploaded.

How it Works:

  • The user selects multiple files using the file input.
  • When the form is submitted, JavaScript triggers the AJAX request to send the files to the PHP script.
  • The progress bar is updated in real-time as files are uploaded.
  • Once the upload is complete, a message is shown for each file, indicating whether it was uploaded successfully or if there was an error.

Let me know if you need further customizations!

Related Post

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Must Read

CATEGORY

spot_img