DEV Community

Cover image for Learn how to upload file with Progress bar
Adeleye Ayodeji
Adeleye Ayodeji

Posted on

Learn how to upload file with Progress bar

Did you want to show a progress bar to your user while uploading images, files, and documents? Then this tutorial is for you.

Video: https://youtu.be/cP--bfz3amM

Watch till end

Code

Upload.php

<?php
header("Content-Type: application/json");
if(isset($_POST)){
    $folder = "./uploads/". basename($_FILES["image"]["name"]);
    if(move_uploaded_file($_FILES["image"]["tmp_name"], $folder)){
        echo json_encode(["code" => 200, "info" => "Image uploaded"]);
    }else{
        echo json_encode(["code" => 401, "info" => "Unable to upload image"]);
    }
}
Enter fullscreen mode Exit fullscreen mode

index.php

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

    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
            integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>AJAX IMAGE UPLOAD WITH PROGRESS BAR</title>
    </head>

    <body>
        <h1>AJAX IMAGE UPLOAD WITH PROGRESS BAR</h1>

        <form id="uploadimage" class="p-3">
            <div class="form-group">
                <label for="">Upload File</label>
                <input type="file" name="image" id="" class="form-control">
            </div>
            <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>
            <button class="btn btn-primary mt-2">Upload</button>
        </form>


        <!-- Optional JavaScript; choose one of the two! -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

        <!-- Option 1: Bootstrap Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
        </script>

        <!-- Option 2: Separate Popper and Bootstrap JS -->
        <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
            integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous">
        </script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
            integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous">
        </script>


        <script>
        $(document).ready(function() {
            $("#uploadimage").submit(function(e) {
                e.preventDefault();
                let form = new FormData(this);
                if ($(this).find("input[name='image']").val() == "") {
                    alert("Select an image");
                    return;
                }
                //AJAX
                $.ajax({
                    type: "POST",
                    url: "upload.php",
                    data: form,
                    cache: false,
                    contentType: false,
                    processData: false,
                    beforeSend: () => {
                        $(".progress").slideDown();
                        $("#uploadimage").find("button").text("Uploading....");
                    },
                    xhr: function() {
                        let xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", (evt) => {
                            //Check for progress
                            if (evt.lengthComputable) {
                                let percentage = (evt.loaded / evt.total) * 100;
                                //100%
                                let percentageformatted = percentage.toFixed(0);
                                //progress bar initialize
                                $(".progress-bar").css("width",
                                    `${percentageformatted}%`).attr(
                                    "aria-valuenow", percentageformatted).text(
                                    `${percentageformatted}%`);
                            }
                        }, false);
                        return xhr;
                    },
                    success: function(response) {
                        $(".progress-bar").addClass("bg-success");
                        $("#uploadimage").find("button").text("Upload");
                    }
                });
            });
        });
        </script>
    </body>

</html>
Enter fullscreen mode Exit fullscreen mode

Discussion (0)