不言不语

您现在的位置是: 首页 >  PHP

PHP

ThinkPHP实现文件下载的方法

2022-06-01PHP
ThinkPHP实现文件下载的方法

ThinkPHP实现文件下载的方法,代码如下:


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;
	}

	$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;
}


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

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

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

 

通过fopen打开文件

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

文章评论