Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to show uploader status bar for image uploading?

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 390
    Comment on it

    Hello Reader's if you are looking for the image uploader status then this blog is very helpful to you.

    The main reason why the developers are using this notifications is because for the user having the slow internet connections they don't want to sit on the browser idle just to wait their file to get uploaded. So its a better user enhancement are by which user can see what going on server side.

    Although you can perform many other features with html 5 also. But remember still html5 is not considered a standard development. Reason why is this browser platform dependence. So one the best is describe is here in this blog.

    Lets consider the ver5.4 or more, we will use session.upload_progress. In this blog we'll see how to make a single uploader status bar without importing any php library or any plugins.

    Session Upload Progress

    Here you have to consider other than uploading only image details there are other two params also which you have to set in session, ie Thesession.upload_progress.enabled this you have to set enable(if not) and put a hidden field in session. The session.upload_progress.name directive. Whensession.upload_progress.enabled is true (on php 5.4) and$_POST[session.upload_progress.name] is sent during an upload, information about the file transfer is made available in the $_SESSION superglobal array.

    The print_r() output of the $_SESSION array will look similar to the following during a file transfer:

    Array
    (
        [upload_progress_myForm] => Array
            (
                [start_time] => 1475738855
                [content_length] => 1254784689
                [bytes_processed] => 245876359
                [done] => 
                [files] => Array
                    (
                        [0] => Array
                            (
                                [name_field] => userfile
                                [name] => file_name.ext
                                [tmp_name] => 
                                [error] => 0
                                [done] => 
                                [start_time] => 1323733740
                                [bytes_processed] => 263178026
                            )
                    )
            )
    )

     

    Create the Form

    Now create the html form and name it to form.php. Its code will be go like this:-

     

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
        // move_uploaded_file()
    }
    ?>
    <html>
     <head>
      <title>Learning the image upload notification</title>
      <link rel="stylesheet" type="text/css" href="style.css">
     </head>
     <body>
      <div id="bar_blank">
       <div id="bar_color"></div>
      </div>
      <div id="status"></div>
      <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" 
       id="myForm" enctype="multipart/form-data" target="hidden_iframe">
       <input type="hidden" value="myForm"
        name="<?php echo ini_get("session.upload_progress.name"); ?>">
       <input type="file" name="userfile"><br>
       <input type="submit" value="Start Upload">
      </form>
      <iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
      <script type="text/javascript" src="script.js"></script>
     </body>
    </html>

     

    After the head section which provides the page’s title and includes the stylesheet, you’ll notice a small collection of div elements. The div with the ID “bar_blank” is the container for the progress bar. The div with the ID “bar_color” will be dynamically updated as the file upload progresses. The “status” div will display the numeric value of the percent uploaded.

    The form is set to submit to the same URL and its target attribute points to a hidden iframe element. Submitting a form to a hidden frame allows you to keep the visitor on the same page while the work is being done in the background. In fact, this is a common practice when doing “Ajax file uploads” since it isn’t possible to send the contents of a file directly using JavaScript’s XmlHttpRequest object.

    Within the form, the special hidden field needed to populate the $_SESSION array appears, followed by a file upload input and submit button. Submitting the form will trigger a JavaScript function namedstartUpload() which will be defined by the included JavaScript file.

    At the bottom of the page is the hidden frame to which the form will post and the import of thescript.js file.

    Add Some Style

    Now you just have to add some CSS to it. And it's code will go like this:-

    #bar_blank {
      border: solid 1px #000;
      height: 20px;
      width: 300px;
    }
    
    #bar_color {
      background-color: #006666;
      height: 20px;
      width: 0px;
    }
    
    #bar_blank, #hidden_iframe {
      display: none;
    }

    Now The JS part. Create a file scprit.js and paste the following code in it.

    function toggleBarVisibility() {
        var e = document.getElementById("bar_blank");
        e.style.display = (e.style.display == "block") ? "none" : "block";
    }
    
    function createRequestObject() {
        var http;
        if (navigator.appName == "Microsoft Internet Explorer") {
            http = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            http = new XMLHttpRequest();
        }
        return http;
    }
    
    function sendRequest() {
        var http = createRequestObject();
        http.open("GET", "progress.php");
        http.onreadystatechange = function () { handleResponse(http); };
        http.send(null);
    }
    
    function handleResponse(http) {
        var response;
        if (http.readyState == 4) {
            response = http.responseText;
            document.getElementById("bar_color").style.width = response + "%";
            document.getElementById("status").innerHTML = response + "%";
    
            if (response < 100) {
                setTimeout("sendRequest()", 1000);
            }
            else {
                toggleBarVisibility();
                document.getElementById("status").innerHTML = "Done.";
            }
        }
    }
    
    function startUpload() {
        toggleBarVisibility();
        setTimeout("sendRequest()", 1000);
    }
    
    (function () {
        document.getElementById("myForm").onsubmit = startUpload;
    })();

     

    Now last part is the action file for the form. Create a new php file and name it to progress.php

    <?php
    session_start();
    
    $key = ini_get("session.upload_progress.prefix") . "myForm";
    if (!empty($_SESSION[$key])) {
        $current = $_SESSION[$key]["bytes_processed"];
        $total = $_SESSION[$key]["content_length"];
        echo $current < $total ? ceil($current / $total * 100) : 100;
    }
    else {
        echo 100;
    }

    This js file will calculate the  file bytes transfered to total file bytes the file and make its percentage.

    And in the bottom of page the div will appear with showing the status of image file being uploading.

 1 Comment(s)

  • does not work properly in IE. Say you have an iframe where you upload the file to, and switch the iframe from uploading the file to another URL where it should cancel the upload immediately, the if (!empty($_SESSION ... will keep returning the percentage left when you cancelled the upload.. for about 5 minutes. Then it will send a full completed bytes after a pause and many URL cycles.

    Also, if you have Kaspersky anti virus running on top of that, IE will FREEZE completely because it piggybacks your iframe URL and sends it to it's own WS:// websocket server for processing. If not running, the pause will finish properly. The quickest way to cancel a file upload is to change the iframe URL to your php "cancel" command if you need to, or just another URL. This kills the session, and sends completed bytes automatically cancelling the file upload. Works on all browsers other than IE with that issue.

    If anyone has found a work-around for IE for that issue, please share with us!
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: