完整代码:
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判断文件是否存在,如果不存在则输出错误信息
立即学习“PHP免费学习笔记(深入)”;
通过fopen打开文件
在更具Header方法处理打开文件,以及通过fread()方法把文件输出。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号