Home ยป Upload Multiple Files with a Progress Bar in PHP and JavaScript
upload-multiple-files-php-javascript
PHP

Upload Multiple Files with a Progress Bar in PHP and JavaScript

Introduction

In the fast-evolving landscape of web development, providing users with the ability to upload multiple files is no longer a luxury; it’s a necessity. Whether you’re building a social media platform, a cloud storage service, or an e-commerce website, allowing users to upload multiple files is a common requirement. This blog post will guide you through the process of implementing a robust “Upload Multiple Files” functionality in your web application using PHP and JavaScript.

What Will You Learn?

In this blog post, you will learn how to create a user-friendly “Upload Multiple Files” feature using PHP and JavaScript. We’ll guide you through every step of the process, from setting up your development environment to integrating a progress bar to give users a visual representation of the upload process. By the end of this tutorial, you’ll be equipped with the skills to implement and customize this feature in your web application.

So, whether you’re a seasoned developer looking to enhance your skills or a beginner eager to understand the intricacies of file uploads, this guide is for you. Let’s get started!

Understanding File Uploads

Before we dive into the technical details of implementing multiple file uploads, let’s take a moment to understand the fundamental concepts behind file uploads on the web.

The Challenges of Multiple File Uploads

While single file uploads are relatively straightforward to handle, multiple file uploads introduce complexity. Here are some of the challenges you might encounter:

  1. User Experience: Providing a smooth and intuitive interface for users to select and upload multiple files can be challenging.
  2. Server Handling: Managing multiple files on the server side, including validation, storage, and security, requires careful implementation.
  3. Feedback and Progress: Users expect feedback during the upload process, including progress indicators, success messages, and error handling.

In this guide, we will address these challenges and guide you through the process of implementing a feature that allows users to upload multiple files seamlessly. We’ll start by setting up your development environment and then move on to handling file uploads in PHP and incorporating a progress bar in JavaScript to enhance the user experience.

Let’s explore the world of multiple file uploads in web development, starting with setting up your development environment.

Technologies Used

In this tutorial, we utilize a combination of various technologies to create a seamless “Upload Multiple Files with a Progress Bar” feature. The following technologies play a crucial role in this implementation:

  1. HTML: We leverage HTML for creating the structure of our file upload form, including the necessary input fields and elements.
  2. Bootstrap 5 Stylesheet: The Bootstrap framework is used for enhancing the user interface and providing a clean and responsive design for the file upload form.
  3. Vanilla JavaScript: We employ vanilla JavaScript to handle the client-side functionality of the progress bar, AJAX requests, and user interactions.
  4. Ajax: AJAX (Asynchronous JavaScript and XML) is a key component for making asynchronous requests to the server, enabling us to update the progress bar without page reloads.
  5. PHP: On the server-side, PHP is the scripting language responsible for handling file uploads, processing data, and managing server-side operations.

By combining these technologies, we create a powerful and user-friendly file upload system that enhances the user experience and streamlines the process of uploading multiple files with a progress bar. Let’s dive deeper into each of these technologies in the tutorial.

File Uploading with a Progress Bar

We will start by creating an HTML form with a progress bar for uploading files.

Create index.php file

To create an index.php file with a form containing a file input and a progress bar for showing the upload progress, you can use the following example code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload with Progress Bar</title>
    <!-- Include Bootstrap 5 stylesheet -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-5">
        <h1 class="mt-3 mb-3 text-center"> Upload Multiple Files </h1>

        <div class="card">
            <div class="card-header">Select File</div>
            <div class="card-body">
                <form id="upload-form" enctype="multipart/form-data" method="post">
                    <table class="table">
                        <tr>
                            <td width="50%" align="right"><b>Select Files (Max 10, Image only, < 3MB)</b>
                            </td>
                            <td width="50%">
                                <input type="file" id="select_file" name="images[]" multiple accept="image/*" />
                            </td>
                        </tr>
                    </table>
                    <div class="text-center">
                        <p id="file-count-info" class="text-muted">No files selected</p>
                        <input type="submit" value="Upload" class="btn btn-primary">
                    </div>
                </form>
            </div>
        </div>
        <br />
        <div class="progress" id="progress_bar" style="display:none; ">
            <div class="progress-bar" id="progress_bar_process" role="progressbar" style="width:0%">0%</div>
        </div>
        <div id="uploaded_image" class="row mt-5"></div>
    </div>
</body>

</html>

Include JavaScript with Ajax to manage “real time” progress.

Without refreshing the browser, the javaScript code that follows transfers data from the chosen file to the server-side script.

<script>
        var fileInput = document.getElementById('select_file');
        var fileCountInfo = document.getElementById('file-count-info');

        fileInput.addEventListener('change', updateFileCount);

        function updateFileCount() {
            var selectedFiles = fileInput.files;
            fileCountInfo.innerText = selectedFiles.length + ' file(s) selected';
        }

        document.getElementById('upload-form').addEventListener('submit', function(event) {
            event.preventDefault();

            var form = this;
            var files = form.querySelector('#select_file').files;
            var maxFiles = 10;
            var maxFileSize = 3 * 1024 * 1024; // 3 MB
            var allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

            if (files.length === 0) {
                alert('Please select at least one file.');
                resetFileInput();
                return;
            }

            if (files.length > maxFiles) {
                alert('You can select a maximum of ' + maxFiles + ' files.');
                resetFileInput();
                return;
            }

            for (var i = 0; i < files.length; i++) {
                var file = files[i];

                if (file.size > maxFileSize) {
                    alert('File size must be less than 3 MB.');
                    resetFileInput();
                    return;
                }

                if (allowedTypes.indexOf(file.type) === -1) {
                    alert('File type not allowed. Please select JPEG, PNG, or GIF images only.');
                    resetFileInput();
                    return;
                }
            }

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

            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percent = (e.loaded / e.total) * 100;
                    document.getElementById('progress_bar').style.display = 'block';
                    document.getElementById('progress_bar_process').style.width = percent + '%';
                    document.getElementById('progress_bar_process').innerHTML = Math.round(percent) + '% completed';
                }
            };

            xhr.onload = function() {
                if (xhr.status === 200) {
                    document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-success">' + xhr.responseText + '</div>';
                    resetFileInput();
                } else {
                    document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">Upload failed</div>';
                    resetFileInput();
                }
            };

            var formData = new FormData(form);
            xhr.send(formData);
        });

        function resetFileInput() {
            document.getElementById('select_file').value = '';
        }
</script>

To use AJAX to handle file uploads, create the upload.php file.

The upload.php file is accessed in response to an Ajax request, which manages the PHP file upload process.
In order to upload the files, we will now also create a “uploads” folder under the current working directory.

<?php
if (!isset($_FILES['images'])) {
    echo 'No files were selected';
    exit;
}

$uploaded_images = [];
$target_dir = "uploads/";
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];

foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
    $file_name = $_FILES['images']['name'][$key];
    $file_size = $_FILES['images']['size'][$key];
    $file_tmp = $_FILES['images']['tmp_name'][$key];

    if ($file_name == "" || !in_array($_FILES['images']['type'][$key], $allowed_types)) {
        continue;
    }

    if ($file_size > 3 * 1024 * 1024) {
        continue;
    }

    $target_file = $target_dir . basename($file_name);

    if (!move_uploaded_file($file_tmp, $target_file)) {
        continue;
    }

    $uploaded_images[] = $file_name;
}

if (empty($uploaded_images)) {
    echo 'No valid files were uploaded';
    exit;
}

if (count($uploaded_images) == 1) {
    echo 'File Uploaded Successfully: ' . implode(', ', $uploaded_images);
} else {
    echo 'Files Uploaded Successfully: <br>';
    foreach ($uploaded_images as $key => $value) {
        echo ($key + 1) . '. ' . $value . "<br>";
    }
}

Note: Ensure that your uploads folder is present.

That’s over. Simply launch your browser, navigate to your index.php file, and upload the files. The screenshot of the file uploading process with the progress bar is shown below.

upload multiple files

Conclusion

In this blog post, we’ve explored the essential aspects of implementing a “Upload Multiple Files” functionality in your web application. Here’s a quick recap of the key takeaways:

  • Importance: Multiple file uploads are vital for various web applications and enhance the user experience.
  • Development Process: We guided you through setting up your environment, handling uploads in PHP, and creating a progress bar with JavaScript.
  • Testing and Debugging: Thoroughly test your implementation, and be prepared to troubleshoot common issues.
  • Enhancing User Experience: Additional features like file type validation and responsive design can make your file upload feature user-friendly.

Now, it’s your turn to implement and customize this feature to meet your application’s needs. Don’t forget to ensure security and user feedback, making the process smooth and secure.

Additional Resources

For further learning and reference, here are some valuable resources to explore:

Q&A and Comments

We encourage you to ask questions, share your experiences, and engage with the community in the comments section below. If you have any challenges or insights related to implementing file uploads, feel free to join the discussion. Happy coding!

Add Comment

Click here to post a comment

+ 17 = 19