PHP Ajax Upload Progress Bar

后端 未结 6 1257
自闭症患者
自闭症患者 2020-11-30 22:56
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 23:42

    Introduction

    The PHP Doc is very detailed it says

    The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.

    All the information you require is all ready in the PHP session naming

    • start_time
    • content_length
    • bytes_processed
    • File Information ( Supports Multiple )

    All you need is to extract this information and display it in your HTML form.

    Basic Example

    a.html

    
    
    
    
    

    b.php

    session_start();
    header('Content-type: application/json');
    echo json_encode($_SESSION["upload_progress_upload"]);
    

    Example with PHP Session Upload Progress

    Here is a better optimized version from PHP Session Upload Progress

    JavaScript

    $('#fileupload').bind('fileuploadsend', function (e, data) {
        // This feature is only useful for browsers which rely on the iframe transport:
        if (data.dataType.substr(0, 6) === 'iframe') {
            // Set PHP's session.upload_progress.name value:
            var progressObj = {
                name: 'PHP_SESSION_UPLOAD_PROGRESS',
                value: (new Date()).getTime()  // pseudo unique ID
            };
            data.formData.push(progressObj);
            // Start the progress polling:
            data.context.data('interval', setInterval(function () {
                $.get('progress.php', $.param([progressObj]), function (result) {
                    // Trigger a fileupload progress event,
                    // using the result as progress data:
                    e = document.createEvent('Event');
                    e.initEvent('progress', false, true);
                    $.extend(e, result);
                    $('#fileupload').data('fileupload')._onProgress(e, data);
                }, 'json');
            }, 1000)); // poll every second
        }
    }).bind('fileuploadalways', function (e, data) {
        clearInterval(data.context.data('interval'));
    });
    

    progress.php

    $s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
    $progress = array(
            'lengthComputable' => true,
            'loaded' => $s['bytes_processed'],
            'total' => $s['content_length']
    );
    echo json_encode($progress);
    

    Other Examples

    • Tracking Upload Progress with PHP and JavaScript
    • PHP-5.4-Upload-Progress-Example

提交回复
热议问题