PHP基础文件下载类的简单封装

时间:2023-03-09 09:19:48
PHP基础文件下载类的简单封装
   1: <?php

   2: /**

   3:  * [FileDown 公用文件下载方法]

   4:  * @param [type] $filePath [文件路径(绝对路径或相对路径)]

   5:  */

   6: function FileDown($filePath)

   7: {

   8:     //由于php中的文件函数默认只支持gb2312编码的中文,这里使用iconv()函数转码为GB2312编码

   9:     $filePath = iconv("UTF-8", "GB2312//IGNORE", $filePath);

  10:  

  11:     //检测文件是否存在:

  12:     if(!file_exists($filePath)){

  13:         die("文件不存在!");

  14:     }

  15:  

  16:     //打开文件:

  17:     $file = @fopen($filePath, "r");

  18:  

  19:     // 获取文件大小

  20:     $fileSize = filesize($filePath);

  21:     

  22:     //获取文件名

  23:     $fileName =get_basename($filePath);

  24:  

  25:  

  26:     //添加响应头信息

  27:     header("Content-Type: application/octet-stream");//返回类型:二进制文件流

  28:     header("Accept-Ranges: bytes");    //告诉客户端以字节数组接受

  29:     header("Accept-Length: $fileSize");    //告诉客户端需要接受的文件大小

  30:     header("Content-Disposition: attachment; filename=".$fileName);//设置下载对话框中显示的文件名

  31:  

  32:     //循环读取指定大小的文件数据返回给客户端

  33:     $buffer=1024;

  34:     $sendCount=0;

  35:     while (!feof($file)&&($fileSize-$sendCount>0)) {

  36:         $sendCount+=$buffer;

  37:         echo fread($file, $buffer);//每次读取1024字节的文件数据返回给客户端

  38:     }

  39:  

  40:     // 关闭文件流

  41:     fclose($file);

  42: }

  43:  

  44: //根据文件路径获取文件的扩展名

  45: function get_extension($filePath)

  46: {

  47:     return pathinfo($filePath, PATHINFO_EXTENSION);

  48: }

  49:  

  50: //根据文件路径获取文件名

  51: function get_basename($filePath)

  52: {

  53:     //使用正则表达式将文件名之前的内容替换为"",返回结果

  54:     return preg_replace('/^.+[\\\\\\/]/', '', $filePath);

  55: }

  56:  

  57: ?>

调用示例:

   1: <?php

   2:     //添加引用

   3:     require_once("FileDownService.php");

   4:  

   5:     //设置客户端页面编码

   6:      header("Content-Type:text/html; charset=utf-8");

   7:  

   8:     //从Request中取出fiLeName参数

   9:     if(isset($_REQUEST["fileName"]))

  10:     {

  11:         //设置文件的绝路径

  12:         $filePath = $_SERVER["DOCUMENT_ROOT"]."/downfiles/".$_REQUEST["fileName"];

  13:  

  14:         //调用文件下载方法进行下载

  15:         FileDown($filePath);

  16:     }

  17:  

  18: ?>