实现“下载文件”功能

jerry thinkphp 2015年11月18日 收藏
验证用户权限后调用此函数可以下载文件,文件可以放在任意位置。
客户端不会出现乱码
不会知道所下载文件真实路径。


  1. /**
  2.  * 下载文件
  3.  * @param string $file
  4.  *               被下载文件的路径
  5.  * @param string $name
  6.  *               用户看到的文件名
  7.  */
  8. function download($file,$name=''){
  9.     $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);
  10.     $filePath = realpath($file);
  11.     
  12.     $fp = fopen($filePath,'rb');
  13.     
  14.     if(!$filePath || !$fp){
  15.         header('HTTP/1.1 404 Not Found');
  16.         echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";
  17.         exit;
  18.     }
  19.     
  20.     $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
  21.     $encoded_filename = urlencode($fileName);
  22.     $encoded_filename = str_replace("+", "%20", $encoded_filename);
  23.     
  24.     header('HTTP/1.1 200 OK');
  25.     header( "Pragma: public" );
  26.     header( "Expires: 0" );
  27.     header("Content-type: application/octet-stream");
  28.     header("Content-Length: ".filesize($filePath));
  29.     header("Accept-Ranges: bytes");
  30.     header("Accept-Length: ".filesize($filePath));
  31.     
  32.     $ua = $_SERVER["HTTP_USER_AGENT"];
  33.     if (preg_match("/MSIE/", $ua)) {
  34.         header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
  35.     } else if (preg_match("/Firefox/", $ua)) {
  36.         header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
  37.     } else {
  38.         header('Content-Disposition: attachment; filename="' . $fileName . '"');
  39.     }
  40.     
  41.     // ob_end_clean(); <--有些情况可能需要调用此函数
  42.     // 输出文件内容
  43.     fpassthru($fp);
  44.     exit;
  45. }