您现在的位置是:首页 > 其他

李清波 2015-10-10 其他 39286 复制当前网址

PHP文件下载



完整代码:

public function downloadFile(){
        $M = M($this->tableName);
        $map['id'] = I('fileId');
        $info = $M->where($map)->find();
        $filepath = '.'.$info['path'];
        if( !file_exists($filepath) ){
            echo '文件不存在!';
            exit;
        }

        //$M->where($map)->setInc('download');
        $file = fopen($filepath,"r"); // 打开文件
        // 输入文件标签
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: ".filesize($filepath));
        Header("Content-Disposition: attachment; filename=" . $info['savename']);
        // 输出文件内容
        echo fread($file,filesize($filepath));
        fclose($file);
        exit;
}


以上代码为thinkphp下的方法


$this->tableName 为存储文件的数据表

根据fileId获取数据库响应文件

通过file_exists判断文件是否存在,如果不存在则输出错误信息


通过fopen打开文件

在更具Header方法处理打开文件,以及通过fread()方法把文件输出。


以上方法如有不明白支出,可以留言一起讨论。

文章来源:http://liqingbo.com/blog-284.html

评论