php实现查询上传文件进度
参考:http://www.ultramegatech.com/2010/10/create-an-upload-progress-bar-with-php-and-jquery/
When it comes to uploading files, users expect visual feedback, usually in the form of a progress bar. The problem is that PHP doesn’t offer a way to track file uploads in progress by default. Fortunately, there is an extension that enables this functionality and this tutorial will show how it can be combined with jQuery UI to create a progress bar.
Here is a demo of the effect we will be building in this tutorial:
Introduction and Setup
In this tutorial, we will be making use of the jQuery UI Progressbar widget and theuploadprogress extension for PHP together to create a visual indicator of file upload progress.
Before we start, you should get your file structure set up. You'll need three empty PHP files:index.php, upload.php and getprogress.php. You'll also need a directory to hold the uploaded files. Here is what the file structure should look like:

If you are using a local copy of jQuery UI, make sure it includes the Progressbar widget.
Step 1: Install The uploadprogress Extension
The first thing we need to do is make sure the required extension, uploadprogress, is installed. Since this is a PECL extension, you use the standard installation procedure for PECL extensions, which is similar to PEAR.
Check For The Extension
The easiest way to find out if the extension is available is to call the phpinfo() function. Create a PHP file on your server containing:
<?php phpinfo(); ?> |
and visit the page with a browser. Search for a section titled "uploadprogress", which will look something like this:

If you find it, congratulations, you already have the required extension! If not, read on.
Be sure to remove the phpinfo file when you are finished!
Get The Extension
The easiest way to get the extension is to run the following command as a root or administrative user:
pecl install uploadprogress |
Assuming there are no errors, this will download and compile the extension. If you get a "command not found" error, you'll need to install PECL using the method appropriate for your distribution and try again.
Here is what the last part of the output should look like if the command is successful:

Load The Extension
Now you'll just need to load the extension, which usually means adding a line like the one below to your php.ini file and restarting the web server.
Linux:
extension=uploadprogress.so |
Windows:
extension=uploadprogress.dll |
Some installations have individual ini files for each extension, in which you'd put the above line. For example, you may have to create a file called uploadprogress.ini in /etc/php.d and place the extension directive in there instead of within the main php.ini.
Be sure to restart your web server for the changes to take effect.
Step 2: Create The Upload Form
In order to have an upload to track, we need a form to accept a file upload. This part is fairly basic, but there are a few important things we need to do to make tracking possible. We'll also need to add a place for a progress bar widget.
First, we need to generate a unique string. If the user decides to upload a file, this will be used to identify and track the upload. This should go right at the top of the index.php file:
<?php |
We also need to include jQuery and jQuery UI to power our front-end. Here we include the libraries along with the default jQuery UI theme from the Google CDN:
<!DOCTYPE html> |
Now it's time to create the form in the body:
<form id="upload-form" |
This will show as a basic file selection field with an "Upload" button. However, there are several things to note in the markup that makes everything functional. In our form tag, we have some important attributes:
- method=post: By default, forms use GET so we want to make sure files are sent via POST
- action=upload.php: This specifies the script that will accept the upload from the form
- enctype=multipart/form-data: This is required in order to handle file uploads
- target=upload-frame: This will be an iframe that will accept the form submission in the background, while the main page can still be manipulated
There is also a hidden field that specifies our upload identifier. The uploadprogress extension looks for a field called UPLOAD_IDENTIFIER to decide whether to track the upload, and uses its value as the identifier. This field must come before the file input!
With the form in place we need to add a div for the progress bar, and the iframe I mentioned earlier:
<div id="progress-bar"></div> |
We'll use some CSS in the head to hide these from view:
<style> |
Here's what the entire page should look like:
1 |
<?php |
Note: we will be placing our JavaScript between the empty script tags later.
Step 3: Create The PHP Back-End
Our PHP back-end will consist of two parts, the upload processing script and the progress fetcher. The upload processor will accept the file from the form and the progress fetcher will be called via AJAX to get progress status updates.
Closing PHP tags are only necessary to switch to plain output, and can be omitted in many cases.
Let's get the upload processing script out of the way. Place this in upload.php:
1 |
<?php |
This is your basic file upload skeleton, which simply places the file into an upload directory. In real life you'll want to add some sanity checks here, but that is beyond the scope of this tutorial.
This next part is where things get interesting. Here is the script that will output the current percentage of the file upload, which will be used to update the progress bar. Place this ingetprogress.php:
1 |
<?php |
This simple script calls the uploadprogress_get_info function provided by the uploadprogress extension. This function takes an identifier as a parameter and returns an array of upload status information, or null if none is found. We're only interested in thebytes_uploaded and bytes_total array items so we can calculate the percentage.
If the function returns null, it means one of three things: the upload hasn't started, the upload is complete, or the upload doesn't exist. This script simply assumes the upload is complete and prints 100. It is up to our JavaScript front-end to determine what is really going on.
Step 4: Create the JavaScript Front-End
With all the important pieces in place, we will bring everything together with JavaScript. The front-end will be responsible for creating the progress bar and querying our back-end for status updates.
Here is the basic skeleton of our script:
(function ($) {
|
Our script is contained within this self-invoking function with jQuery passed as a parameter named $. This ensures that the $ jQuery alias is available within our script. We have also declared two variables, one to reference the progress bar element (pbar) and one to determine whether we have started uploading (started).
We need to start the progress bar when the form is submitted, so we will attach a function to the form's submit event:
$(function () {
|
$(function () { })is shorthand for$(document).ready(function () { })
The entire event code is wrapped in a function passed to jQuery, which is equivalent to attaching it to the document ready event. The submit event handler on our form does four things so far:
- Hides the form
- Saves the reference to the progress bar element to the
pbarvariable - Makes the progress bar visible
- Attaches a jQuery UI Progressbar widget the the progress bar div
Still in the submit event function, we need to attach an event to the iframe:
$('#upload-form').submit(function() {
|
Here, we have attached a function to the iframe's load event. The load event is fired when an item has fully loaded, which in this case is when the page within the frame is loaded. Since the iframe is where the form is being submitted, this happens when the upload is complete.
When the load event fires we first set the started flag to true, since we know the upload must have started if it is finished. This is to prevent an infinite loop in case the upload completes before we can start tracking.
In the load event, we also trigger any end actions we want to perform. In this example we simply trigger an alert, but you can do whatever you want here.
The last part of our submit function is where the tracking begins:
$('#upload-form').submit(function() {
|
Here, we have created a one second timeout which will call our (yet to be created) function named updateProgress, to which we pass the value of the upload identifier field. The delay gives the form time to begin sending data before we ask for updates about that data.
Now we must create that updateProgress function, which mostly consists of an AJAX request:
function updateProgress(id) {
|
We are making a GET request to our back-end getprogress.php script, passing two parameters. The first is the upload identifier, uid, which is expected by our back-end. The second is the current timestamp, which simply makes the URL unique to prevent caching. I've found that this is the best way to prevent caching, since cache control headers aren't always reliable.
Since the back-end returns a percentage as an integer, we parse that data and assign it to aprogress variable.
$.get('getprogress.php', { uid: id, t: time }, function (data) {
|
This next part of the callback is where we create the loop:
$.get('getprogress.php', { uid: id, t: time }, function (data) {
|
If the upload progress is not 100% or we haven't started uploading, we will call theupdateProgress function again. We also check if the upload has started and set the startedflag appropriately, which is true as soon as the value is not 100. Now updateProgress will repeat until the upload is complete.
The last part of our callback is where we actually update the progress bar widget. Note the use of the && operator to make sure the code only runs if started is true.
$.get('getprogress.php', { uid: id, t: time }, function (data) {
|
The Final Result
If everything is done correctly, your result should behave like this:
Below is the complete code.
upload.php (example; not production quality)
1 |
<?php |
getprogress.php
1 |
<?php |
index.php
1 |
<?php |
Conclusion
This tutorial describes one method of creating an upload progress bar. Unlike other methods, this one relies very little on the client since no plugins are involved. The only requirement for the progress bar to display is JavaScript. Most of the work is done on the server side.
I hope you find this technique useful in one of your projects. This can be easily expanded by displaying more data from the uploadprogress extension, such as transfer speed and estimated time. If you have any questions or comments, please write a comment below.
php实现查询上传文件进度的更多相关文章
- node实现http上传文件进度条 -我们到底能走多远系列(37)
我们到底能走多远系列(37) 扯淡: 又到了一年一度的跳槽季,相信你一定准备好了,每每跳槽,总有好多的路让你选,我们的未来也正是这一个个选择机会组合起来的结果,所以尽可能的找出自己想要的是什么再做决定 ...
- Ajax上传文件进度条显示
要实现进度条的显示,就要知道两个参数,上传的大小和总文件的大小 html5提供了一个上传过程事件,在上传过程中不断触发,然后用已上传的大 小/总大小,计算上传的百分比,然后用这个百分比控制div框的显 ...
- asp.net大文件上传与上传文件进度条问题
利用Plupload解决大容量文件上传问题, 带进度条和背景遮罩层 关于Plupload结合上传插件jquery.plupload.queue的使用 这是群里面一位朋友给的资料. 下面是自己搜索到的一 ...
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
转载:http://www.cnblogs.com/kivenhou/archive/2013/02/22/2921954.html 操作List前请设置SPWeb的allowUnsafeUpdate ...
- php上传文件进度条
ps:本文转自脚本之家 Web应用中常需要提供文件上传的功能.典型的场景包括用户头像上传.相册图片上传等.当需要上传的文件比较大的时候,提供一个显示上传进度的进度条就很有必要了. 在PHP 5.4以前 ...
- PHP使用APC获取上传文件进度
今天发现使用PHP的APC也能获取上传文件的进度.这篇文章就说下如何做. 安装APC 首先安装APC的方法和其他PHP模块的方法没什么两样,网上能找出好多 phpinfo可以看到APC的默认配置有: ...
- php 使用html5 XHR2 上传文件 进度显示
思路:只要我们知道上传文件的总大小,还有上传过程中上传文件的大小,那么就可以实现进度显示了. 在html5中,XMLHttpRequest对象,传送数据的时候,progress事件用来返回进度信息. ...
- (转载) 上传文件进度事件,进度事件(Progress Events)
转载URL:https://www.w3cmm.com/ajax/progress-events.html MDN参考:https://developer.mozilla.org/zh-CN/docs ...
- ajax上传文件进度条
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
随机推荐
- 下载文件的一致性验证之MD5值校验
前几天写脚本遇到下载功能校验,一时间不到怎么校验好? 于是请教大神,大神给出方案如下: 先去了解一下你们的产品针对这个下载功能有没有做什么功能设计...然后再针对这些功能设计去设计测试用例...比如 ...
- 在Vue中使用计时器笔记
在Vue中使用了计时器,一定要记得在生命周期destroyed()里清掉,不然第二次进入这个组件,会出现很大的问题 destroyed () { // (很重要)当跳转到其他页面的时候,要在生命周期的 ...
- python与redis
1.什么是redis Redis 是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset ...
- listbox或datagrid内容双击事件绑定
====listbox=== <DataTemplate> <Border Width="350" Height="230" Margin=& ...
- python 全栈开发,Day52(关于DOM操作的相关案例,JS中的面向对象,定时器,BOM,client、offset、scroll系列)
昨日作业讲解: 京东购物车 京东购物车效果: 实现原理: 用2个盒子,就可以完整效果. 先让上面的小盒子向下移动1px,此时就出现了压盖效果.小盒子设置z-index压盖大盒子,将小盒子的下边框去掉, ...
- C# int可以表示的最大值
C#中int由4个字节组成,即由32个二进制数组成,由于最高位是用于表示正负数,所以实际上int所能表示的最大数为231-1=2147483647.
- openstack学习-创建一台云主机(七)
一.创建基础环境 1.检查网络是否正常 [root@linux-node1 ~]# openstack network agent list +---------------------------- ...
- CentOS7.5安装nodejs
安装方法1——直接部署 1.首先安装wget yum install -y wget 如果已经安装了可以跳过该步 2.下载nodejs最新的tar包 可以在下载页面https://nodejs.org ...
- Spring bean加载多个配置文件
除了写很简单的加载一个xml,加载多个的情况一直没用到,在公司里也不会由自己处理这个问题,现在需要用到了,就研究验证一下. 使用的案例还是上面的例子. 只有,将原来的beans.xml分成两个部分. ...
- JAVA Socket通信 打造属于自己的网盘
近一个月没敲JAVA代码了,最近老师布置了一个写JAVA网盘的作业,总共花了十几个小时,总算写完了,debug真的累,感觉自己还是菜了,没有那种有一个想法就能马上用代码实现的能力....不扯了,下面开 ...