PHP基础文件下载类的简单封装 调用示例:
1: <?php
/**
* [FileDown 公用文件下载方法]
* @param [type] $filePath [文件路径(绝对路径或相对路径)]
*/
function FileDown($filePath)
7: {
//由于php中的文件函数默认只支持gb2312编码的中文,这里使用iconv()函数转码为GB2312编码
, $filePath);
10:
//检测文件是否存在:
if(!file_exists($filePath)){
);
14: }
15:
//打开文件:
);
18:
// 获取文件大小
20: $fileSize = filesize($filePath);
21:
//获取文件名
23: $fileName =get_basename($filePath);
24:
25:
//添加响应头信息
//返回类型:二进制文件流
//告诉客户端以字节数组接受
//告诉客户端需要接受的文件大小
//设置下载对话框中显示的文件名
31:
//循环读取指定大小的文件数据返回给客户端
33: $buffer=1024;
34: $sendCount=0;
while (!feof($file)&&($fileSize-$sendCount>0)) {
36: $sendCount+=$buffer;
//每次读取1024字节的文件数据返回给客户端
38: }
39:
// 关闭文件流
41: fclose($file);
42: }
43:
//根据文件路径获取文件的扩展名
function get_extension($filePath)
46: {
return pathinfo($filePath, PATHINFO_EXTENSION);
48: }
49:
//根据文件路径获取文件名
function get_basename($filePath)
52: {
'', $filePath);
55: }
56:
57: ?>
1: <?php
//添加引用
);
4:
//设置客户端页面编码
);
7:
//从Request中取出fiLeName参数
]))
10: {
//设置文件的绝路径
];
13:
//调用文件下载方法进行下载
15: FileDown($filePath);
16: }
17:
18: ?>