PHP 会话上传进度

PHP 在 5.4.0 之后支持针对服务端的文件上传进度检测:

下面的代码段展示了如何将此功能运用在 FileUpload 插件上:

JavaScript (application.js)

// This code assumes each file upload has a related DOM node
// set as data.context, which is true for the UI version:
$('#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 value:
        var progressObj = {
            name: 'PHP_SESSION_UPLOAD_PROGRESS',
            value: (new Date()).getTime()  // pseudo unique ID
        // Start the progress polling:'interval', setInterval(function () {
            $.get('progress.php', $.param([progressObj]), function (result) {
                // Trigger a fileupload progress event,
                // using the result as progress data:
                e = $.Event( 'progress', {bubbles: false, cancelable: true});
                $.extend(e, result);
                ($('#fileupload').data('blueimp-fileupload') ||
                    $('#fileupload').data('fileupload'))._onProgress(e, data);
            }, 'json');
        }, 1000)); // poll every second
}).bind('fileuploadalways', function (e, data) {

PHP (progress.php)

  // Assuming default values for session.upload_progress.prefix
  // and
  $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);

Alternative PHP Cache (APC)

根据 介绍,PHP 5.2+ 开始支持 APC 功能。在 APC 工具完成安装并正确配置后,旧版浏览器可以通过 teynon 扩展分支启用 APC 文件上传。

想要在该分支启用 apc 功能,只需 apc 配置项设为 true。

    apc: true
译者注:APC 是一种对 PHP 有效的开放源高速缓冲储存器工具,它能够缓存 opcode 的 php 中间代码。