php文件下载(解决文件下载后多几个字节的问题) 与封装成类的例子
php文件下载比较常见,网上的资料比较多,在此不再强调怎么去实现(因为也是网上看的)。下面主要说明的是下载代码的注意点。
php下载文件主要是把文件以字节流直接输出,也就是echo fread($file, filesize($file_name));,这里要注意的是如果你在代码之前(或之后)有输出,也可能被写入下载的文件中,解决的方法是使用 ob_start();和ob_end_clean();来清除前面的输出,后面的输出直接使用@fclose($file);exit(0);来解决。
代码如下:
- ob_start();
- $file_name = iconv("utf-8","gb2312",$file_name);
- if (!is_file($file_name)){
- echo "url error!";
- } else {
- $ua = $_SERVER["HTTP_USER_AGENT"];
- if (preg_match("/MSIE/", $ua)) {
- $encoded_filename = urlencode(basename($file_name));
- $encoded_filename = str_replace("+", "%20", $encoded_filename);
- $con_dis = 'Content-Disposition: attachment; filename="' . $encoded_filename . '"';
- } else if (preg_match("/Firefox/", $ua)) {
- $con_dis = 'Content-Disposition: attachment; filename*="utf8\'\'' . basename($file_name) . '"';
- } else {
- $con_dis = 'Content-Disposition: attachment; filename="' . basename($file_name) . '"';
- }
- $file = fopen($file_name, "r");
- //输入文件标签
- ob_end_clean();Header("Content-type: application/octet-stream");Header("Accept-Ranges: bytes");Header("Accept-Length: ".filesize($file_name));Header($con_dis);
- //输出文件内容
- //读取文件内容并直接输出到浏览器
- echo fread($file, filesize($file_name));@fclose($file);
- exit(0);
- }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
class FileDown { public $fileName ; public $fileSize ; //转码 gb2312 function __construct( $fileName ){ $this ->fileName=iconv( "utf-8" , "gb2312" , $fileName ); } function Down (){ //$_SERVER['DOCUMENT_ROOT']当前运行脚本所在的文档根目录。在服务器配置文件中定义。 $path = $_SERVER [ 'DOCUMENT_ROOT' ]. "/12/" . $this ->fileName; if (! file_exists ( $path )){ die ( "文件不存在" ); } $fp = fopen ( $path , "r" ); //读入 $this -> fileSize = filesize ( $path ); //返回文件的头 浏览器靠头识别下载 //返回 //返回的文件类型 流 可以是文本 二进制 header( "Content-type: application/octet-stream" ); //按照字节大小返回 header( "Accept-Ranges: bytes" ); //返回文件大小 header( "Accept-Length: $this->fileSize" ); //这里客户端的弹出对话框,对应的文件名 header( "Content-Disposition: attachment; filename=" . $this ->fileName); $count =0; $buffer =1024; while (! feof ( $fp )&& $this -> fileSize - $count >0){ $fileData = fread ( $fp , $buffer ); $count += $buffer ; echo $fileData ; } fclose( $fp ); } } $fd = new FileDown( "白羊座.png" ); $fd ->Down (); |