您的位置:首页 > 编程语言 > PHP开发

PHP文件下载

2015-11-07 18:39 567 查看
摘要: PHP的文件下载类

<?php
class Down
{
private $file = '';
private $msg = null;

public function __construct($file,$buffer=1024)
{
// 用以解决中文不能显示出来的问题
$file            = iconv('utf-8','gbk',$file);
$this->file      = $_SERVER['DOCUMENT_ROOT'].'/'.$file;
$this->buffer    = $buffer;
}

public function act()
{
if (!file_exists($this->file))
{
// 如果需要下载的文件不存在
$this->msg = '文件不存在';
return $this->msg;
}

$handle = fopen($this->file,'r');
if (!$handle)
{
// 无法打开文件
$this->msg = '无法打开文件';
return $this->msg;
}

$filesize = filesize($this->file);

// 下载需要的文件头
header('content-type:application/ocet-stream');
header('Accept-Ranges:bytes');
header('Accept-Length:'.$filesize);
header('Content-Disposition:attachment;filename='.$this->file);

$file_count = 0;

// 向浏览器返回数据
while(!feof($handle) && $file_count<$filesize){
$file_down = fread($handle,$this->buffer);
$file_count += $this->buffer;
echo $file_down;
}

// 关闭资源
fclose($handle);
$msg = '下载完毕';
// return $msg;
return $file_down;
}
}
header('content-type:text/html;charset="utf-8"');
header('expire:-1');
header('cache-control:no-cache');
header("pragma:no-cache");
$down = new Down('d:/myblog/test.jpg');
$msg = $down->act();
echo $msg;
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PHP HTTP 文件下载