一个关于php将资源提供进行下载的操作类

最近项目有需求需要定期svn更新项目,并打包成下载包供下载,参考了网上的一些相关代码后写了如下一个用来提供给用户下载的小组件

关于php进行svn操作的组件:http://blog.csdn.net/meeeen7/article/details/78297063

关于php进行zip打包的组件:http://blog.csdn.net/meeeen7/article/details/78297467


class downloadUtil  {
    protected $_filename;
    protected $_filepath;
    protected $_filesize;

    //文件大小
    public function __construct($filepath,$filename){
        $this->_filename=$filename;
        //$this->_filepath=dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/'.$filename;
        $this->_filepath=$filepath;
    }

    //获取文件名
    public function getfilename(){
        return $this->_filename;
    }

    //获取文件路径(包含文件名)
    public function getfilepath(){
        return $this->_filepath;
    }

    //获取文件大小
    public function getfilesize(){
        return $this->_filesize=number_format(filesize($this->_filepath)/(1024*1024),2);//去小数点后两位
    }
    //下载文件的功能
    public function getfiles(){
        //检查文件是否存在
        if (file_exists($this->_filepath)){
            //打开文件
            $file = fopen($this->_filepath,"r");
            //返回的文件类型
            Header("Content-type: application/octet-stream");
            //按照字节大小返回
            Header("Accept-Ranges: bytes");
            //返回文件的大小
            Header("Accept-Length: ".filesize($this->_filepath));
            //这里对客户端的弹出对话框,对应的文件名
            Header("Content-Disposition: attachment; filename=".$this->_filename);
            //修改之前,一次性将数据传输给客户端
            echo fread($file, filesize($this->_filepath));
            //修改之后,一次只传输1024个字节的数据给客户端
            //向客户端回送数据
            $buffer=1024;//
            //判断文件是否读完
            while (!feof($file)) {
                //将文件读入内存
                $file_data=fread($file,$buffer);
                //每次向客户端回送1024个字节的数据
                echo $file_data;
            }

            fclose($file);
        } else {
            echo "<script>alert('对不起,您要下载的文件不存在');</script>";
        }
    }
}

使用时直接new downloadUtil()将要下载文件路径和文件名传入构造函数中,其中getfiles函数中的buffer代表了下载时每次传输的数据量,可自行进行调节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值