PHP File Upload with Progress Bar using jQuery and Ajax

PHP File Upload with Progress Bar using jQuery and Ajax

Introduction:

File uploads are a common feature in web applications but implementing them with progress tracking can be challenging. In this guide, we’ll walk through the process of creating a file upload functionality with a progress bar using PHP, jQuery and ajax. We’ll cover everything from handling file uploads securely to displaying progress to the user in real-time.

This will include basically 3 parts of the code implementation. which are as follows:

  • Frontend (basically HTML section, which interact with the user experience)
  • Backend (to handle the code execution to work as the main part to store the files with error handling and storing the form data)
  • JavaScript/jQuery (Which works as the intermediate between Frontend and Backend to provide smooth workflow and help user to connect with your application more interestingly)

Now, let understand with the help of code below with commented code explanation. Hope you will get this worth reading.

Frontend (Index.php/index.html)

Setting Up the HTML Form (index.html):

  • Begin by creating a standard HTML form to facilitate file uploads.
  • Utilize Bootstrap for structuring the form elements in a visually appealing manner.
  • Include a file input field and a button to trigger the upload process.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
    <!-- Include Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2>Upload File</h2>

        <!-- HTML form for file upload -->
        <form id="fileUploadForm" enctype="multipart/form-data">
            <div class="form-group">
                <input type="file" name="file" id="fileInput" class="form-control-file">
            </div>
            <button id="uploadBtn" type="button" class="btn btn-primary">Upload</button>
            <div class="progress mt-3" style="display: none;">
                <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
            </div>

            <!-- Container for displaying upload status -->
            <div id="uploadStatus" class="mt-3"></div>
        </form>
    </div>
    <!-- Include jQuery -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <!-- Include Bootstrap JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Include script.js for handling form submission -->
    <script src="script.js"></script>
</body>
</html>

Backend (upload.php)

Implementing the Upload Script (upload.php):

  • Begin by setting up error reporting to display all errors for better troubleshooting.
  • Handle file uploads securely by checking for errors and validating file types.
  • Move the uploaded file to the desired destination directory.
  • Return JSON responses for improved error handling and user feedback.
<?php
// Set error reporting to display all errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');

$response = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $response['message'] = 'File upload error: ' . $file['error'];
        http_response_code(400);
    } else {

        // Handle file upload securely
        // Move the uploaded file to the desired destination directory
        // Return JSON responses for error handling and user feedback
        
        $targetDir = 'uploads/';
        $targetFile = $targetDir . basename($file['name']);
        $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

        // Check if the file already exists
        if (file_exists($targetFile)) {
            $response['message'] = 'File already exists';
            http_response_code(400);
        }
        // Check file size (limit to 5MB)
        elseif ($file['size'] > 5 * 1024 * 1024) {
            $response['message'] = 'File size exceeds the limit of 5MB';
            http_response_code(400);
        }
        // Allow only certain file formats
        elseif (!in_array($fileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            $response['message'] = 'Only JPG, JPEG, PNG, and GIF files are allowed';
            http_response_code(400);
        } else {
            if (move_uploaded_file($file['tmp_name'], $targetFile)) {
                $response['filename'] = basename($file['name']);
            } else {
                $response['message'] = 'Error moving file to destination directory';
                http_response_code(500);
            }
        }
    }
} else {
    $response['message'] = 'Invalid request';
    http_response_code(400);
}

echo json_encode($response);
?>

Jquery/JavaScript (script.js)

Writing jQuery Script for Progress Tracking (script.js):

  • Utilize jQuery to handle form submission and initiate file uploads.
  • Check file formats before initiating the upload process to prevent unnecessary progress updates.
  • Implement a progress bar to visually represent the upload progress to users.
  • Display success or error messages based on the upload status.
$(document).ready(function() {
    $('#uploadBtn').click(function() {
        // Retrieve the selected file

        var fileInput = $('#fileInput');
        var file = fileInput[0].files[0];

        // Check if a file is selected
        if (!file) {
            // Display error message if no file is selected
            $('#uploadStatus').html('<div class="alert alert-danger">Please select a file</div>');
            return;
        }

        var allowedFormats = ['jpg', 'jpeg', 'png', 'gif'];
        var fileExtension = file.name.split('.').pop().toLowerCase();

        // Check if the file format is allowed
        if (allowedFormats.indexOf(fileExtension) === -1) {
            $('#uploadStatus').html('<div class="alert alert-danger">Only JPG, JPEG, PNG, and GIF files are allowed</div>');
            return;
        }

        var formData = new FormData($('#fileUploadForm')[0]);

        // Send AJAX request to upload.php for file upload
        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            xhr: function() {
                // Create an XMLHttpRequest object to track upload progress
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(event) {
                    if (event.lengthComputable) {
                        var percent = Math.round((event.loaded / event.total) * 100);
                        $('.progress').show();
                        // Update progress bar with the upload progress
                        $('.progress-bar').css('width', percent + '%').text(percent + '%');
                    }
                });
                return xhr;
            },
            success: function(response) {
                // Handle successful upload
                $('#uploadStatus').html('<div class="alert alert-success">File uploaded successfully: ' + response.filename + '</div>');
            },
            error: function(xhr, status, error) {
                // Handle upload errors
                var errorMessage = xhr.responseJSON ? xhr.responseJSON.message : 'Unknown error';
                $('#uploadStatus').html('<div class="alert alert-danger">Error: ' + errorMessage + '</div>');
            }
        });
    });
});

Conclusion:

By following the comprehensive steps outlined in this guide, you can master the art of implementing file uploads with a progress bar using PHP and jQuery. With a deep understanding of each component and meticulous attention to detail, you’ll be well-equipped to create robust and user-friendly file upload functionalities for your web applications.

You can get more details about ajax event handling here.
To get to know more about other jQuery topics, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply

Share