今天发现使用PHP的APC也能获取上传文件的进度。这篇文章就说下如何做。
安装APC
首先安装APC的方法和其他PHP模块的方法没什么两样,网上能找出好多
phpinfo可以看到APC的默认配置有:
apc.rfc1867
看apc.rfc1867这个配置项:
http://cn2.php.net/manual/en/apc.configuration.php#ini.apc.rfc1867
文档说的是如果你上传文件的时候,在POST中带有APC_UPLOAD_PROGRESS字段,那么APC会自动以这个值创造一个upload_key缓存
这个时候,用户可以使用ajax再过来调用,就可以获取到当前文件上传的状态了
这个状态包括:
文件大小
当前已上传文件大小
文件上传速度(上传结束后才有)
实验:
1 开启rfc1867配置项
apc.rfc1867=on
2 确认,phpinfo()中可以看到已经打开
3 服务端上传php代码
1
2
3
4
5
6
7
8
9
10
11
|
apc.php
<?php
if
(
$_FILES
[
'file'
][
'error'
] == UPLOAD_ERR_OK){
$path
=
'/tmp/upload/'
;
$path
.=
basename
(
$_FILES
[
'file'
][
'name'
]);
if
(move_uploaded_file(
$_FILES
[
'file'
][
'tmp_name'
],
$path
)){
// upload successful
echo
'sucess'
;
}
}
|
确保能通过网络访问到页面
这里可以通过http://10.16.15.118:7702/apc.php 访问
4 服务端查看进度php代码
1
2
3
4
|
getprocess.php
<?php
print_r(apc_fetch(
"upload_6226f7cbe59e99a90b5cef6f94f966fd"
));
|
确保能通过网络访问到页面
这里可以通过http://10.16.15.118:7702/getprocess.php 访问到
5 写个简单的客户端html
1
2
3
4
5
6
7
8
9
|
<html>
<body>
<input type=
"hidden"
name=
"APC_UPLOAD_PROGRESS"
value=
"6226f7cbe59e99a90b5cef6f94f966fd"
/>
<input type=
"file"
name=
"file"
/>
<input type=
"submit"
value=
"submit"
/>
</form>
</body>
</html>
|
这里要注意的是,APC_UPLOAD_PROCESS 必须要放在上传的file之前(这也是文档中有写到的),否则会出现warning,并且也无法得到process
6 上传文件访问apc.php
7 查看getprocess.php
下面的疑问就是是不是真有中间过渡状态呢?
1 找个大文件,(20M+)
2 确认下nginx+php对文件大小限制超过20M
3 开启fidder做限速:
按照这篇文章说的:http://donchevp.blogspot.com/2009/11/limiting-your-internet-connection-speed.html
设置rule - customer - 设置这一段代码
1
2
3
4
5
6
|
if
(m_SimulateModem) {
// Delay sends by 300ms per KB uploaded.
oSession[
"request-trickle-delay"
] =
"1"
;
// Delay receives by 150ms per KB downloaded.
oSession[
"response-trickle-delay"
] =
"150"
;
}
|
修改这个request-trickle-delay
然后开启Simulate模式。
4 a.html页面上传这个20M文件
5 不断刷新getprocess.php
可以看到current的进度,而且可以看到没有上传完成的时候,rate字段是没有的~~~so good~~
本文转自轩脉刃博客园博客,原文链接:http://www.cnblogs.com/yjf512/p/3173457.html,如需转载请自行联系原作者