PHP Ajax上传进度条

23
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="uploaded" type="file" />
<input type="submit" value="Upload" />
</form>

<?php
if(isset($_REQUEST['submit'])){
   $target = "data/".basename( $_FILES['uploaded']['name']) ;
   move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
}
?>

我很擅长JavaScript,AJAX和JQuery等编程语言,并相信可以使用PHP,AJAX和JavaScript等技术创建上传进度条。我想知道如何在上传过程中获取上传文件的大小(即每秒钟上传了多少文件以及剩余多少文件)。我认为可以使用AJAX等技术实现此目的,但不理解PHP手册上的内容:http://php.net/manual/en/session.upload-progress.php。是否有其他方法在不使用任何外部PHP扩展的情况下使用PHP和AJAX显示上传进度条?我无法访问php.ini
6个回答

40

介绍

PHP文档非常详细,它说:

当上传正在进行时,在$_SESSION超全局变量中将可用上传进度,并且当POST一个与session.upload_progress.name INI设置相同的变量名称时,PHP会弹出一个数组到$_SESSION中,其中索引是session.upload_progress.prefix和session.upload_progress.name INI选项的连接值。通常通过读取这些INI设置来检索键。

您需要的所有信息都已经在PHP会话命名中了:

  • start_time
  • content_length
  • bytes_processed
  • 文件信息(支持多个)

您只需要提取此信息并在HTML表单中显示即可。

基本示例

a.html

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
    var intval = null;
    var percentage = 0 ;
    function startMonitor() {
        $.getJSON('b.php',
        function (data) {
            if (data) {
                percentage = Math.round((data.bytes_processed / data.content_length) * 100);
                $("#progressbar").progressbar({value: percentage});
                $('#progress-txt').html('Uploading ' + percentage + '%');

            }
            if(!data || percentage == 100){
                $('#progress-txt').html('Complete');
                stopInterval();
            }
        });
    }

    function startInterval() {
        if (intval == null) {
            intval = window.setInterval(function () {startMonitor()}, 200)
        } else {
            stopInterval()
        }
    }

    function stopInterval() {
        if (intval != null) {
            window.clearInterval(intval)
            intval = null;
            $("#progressbar").hide();
            $('#progress-txt').html('Complete');
        }
    }

    startInterval();
</script>

b.php

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

使用PHP会话上传进度的示例

这是一份更优化的版本,源自PHP会话上传进度

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'));
});

进度.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);

其他示例


对我来说不起作用。此外,链接已过时。 - ashleedawg

4

以下是我的代码,它可以正常运行 试一下:

演示网址 (链接失效)

http://codesolution.in/dev/jQuery/file_upload_with_progressbar/

试试下面的代码:

HTML:

<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }

.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
    <h1>File Upload Progress Demo #1</h1>
    <code>&lt;input type="file" name="myfile"></code>
        <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadedfile"><br>
        <input type="submit" value="Upload File to Server">
    </form>

    <div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
    </div>

    <div id="status"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    complete: function(xhr) {
     bar.width("100%");
    percent.html("100%");
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

</body>
</html>

upload.php :

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

uploadProgress不是一个ajax选项,但你可以使用这个代替: https://dev59.com/zZ_ha4cB1Zd3GeqPth2r - JuliSmz

3

我可以建议你使用FileDrop

我用它来制作进度条,非常容易。

唯一的缺点是在处理大量数据时会遇到一些问题,因为它似乎不能清除旧文件 - 可以手动修复。

虽然不是用 JQuery 编写的,但它仍然很好用,作者回答问题也很快。


2

虽然编写进度条的代码可能很有趣,但为什么不选择现有的实现呢?Andrew Valums编写了一个非常好的实现,您可以在这里找到:

http://fineuploader.com/

我在所有项目中都使用它,它的效果非常棒。


1
我也用它来做一些项目。工作得非常好。 - EmeraldCoder
我知道这个答案有点老了,所以请原谅我,但是你不是必须要为fineuploader付费吗? - pattyd
源代码在此处以GNU GPL v3许可证提供:https://github.com/Widen/fine-uploader - Joram van den Boezem

-1

XMLHTTPREQUSET2

var xhr = new XMLHttpRequest();
xhr.open('GET', 'video.avi', true);
xhr.responseType = 'blob';

xhr.onload = function(e) {
  if (this.status == 200) {
    var blob = this.response;
/*
    var img = document.createElement('img');
    img.onload = function(e) {
      window.URL.revokeObjectURL(img.src); // Clean up after yourself.
    };
    img.src = window.URL.createObjectURL(blob);
    document.body.appendChild(img);
    /*...*/
  }
};
xhr.addEventListener("progress", updateProgress, false);
xhr.send();



function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
    var percentComplete = oEvent.loaded / oEvent.total;
    console.log(percentComplete)
  } else {
    // Unable to compute progress information since the total size is unknown
  }
}

-1
首先,确保您的计算机上安装了PHP 5.4。您没有标记,所以我不知道。通过调用echo phpversion();(或从命令行调用php -v)来检查。
无论如何,假设您有正确的版本,您必须能够在php.ini文件中设置正确的值。既然您说您不能这样做,那么我就不值得解释如何做了。
作为备选方案,请使用Flash对象上传器。

我知道如何更改php.ini,但问题是我没有访问php.ini的权限,而且我不想使用Flash,甚至无法升级php到最新版本。 - Wasim A.
如果你的PHP版本不正确,就别试图让它工作了。它不会工作的,就这样。这个功能只在最新的PHP版本中添加。 - Niet the Dark Absol
除了session.upload-progress方法之外,是否还有其他方法?我认为在PHP 5.4之前,许多网站都包含进度条。 - Wasim A.
那些网站使用其他方法,通常是基于Flash的。一些较新的浏览器支持有关文件的某些内容,但我对此了解不多。 - Niet the Dark Absol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接