thinkphp,下载附件

时间:2023-01-14 04:22:59

ThinkPHP框架下有个Org/Net/Http.class.php的方法download。

thinkphp,下载附件

Http.class.php的download方法如下

/**
* 下载文件
* 可以指定下载显示的文件名,并自动发送相应的Header信息
* 如果指定了content参数,则下载该参数的内容
* @static
* @access public
* @param string $filename 下载文件名
* @param string $showname 下载显示的文件名
* @param string $content 下载的内容
* @param integer $expire 下载内容浏览器缓存时间
* @return void
*/
static public function download ($filename, $showname='',$content='',$expire=180) {
if(is_file($filename)) {
$length = filesize($filename);
}elseif(is_file(UPLOAD_PATH.$filename)) {
$filename = UPLOAD_PATH.$filename;
$length = filesize($filename);
}elseif($content != '') {
$length = strlen($content);
}else {
E($filename.L('下载文件不存在!'));
}
if(empty($showname)) {
$showname = $filename;
}
$showname = basename($showname);
if(!empty($filename)) {
$finfo = new \finfo(FILEINFO_MIME);
$type = $finfo->file($filename);
}else{
$type = "application/octet-stream";
}
//发送Http Header信息 开始下载
header("Pragma: public");
header("Cache-control: max-age=".$expire);
//header('Cache-Control: no-store, no-cache, must-revalidate');
header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
header("Content-Disposition: attachment; filename=".$showname);
header("Content-Length: ".$length);
header("Content-type: ".$type);
header('Content-Encoding: none');
header("Content-Transfer-Encoding: binary" );
if($content == '' ) {
readfile($filename);
}else {
echo($content);
}
exit();
}

首先需要看一下大家使用的Thinkphp的版本,不同的版本使用的方法不同,(在导入公共函数的时候方式不同)

我用的是thinkphp3.2.3版本的,因此直接使用import()函数,直接把使用thinkphp自带的http类的功能实现下载。但是在引用公共类的时候,

首先需要使用import来导出公共类,import('ORG.Net.Http');。接下来最重要的是需要重新new一下,否则无法使用类。$http = new \Org\Net\Http();

然后接下来就需要把需要下载的文件路径注明。(必须使用绝对路径)。

我写的代码如下:

/*
* 下载文件
*/
public function download(){
if(IS_GET){
$id=i('id');
$res=D('Activities')->where("id='{$id}'")->find();
import('ORG.Net.Http');
$http = new \Org\Net\Http();
$http->download($res['attachment']);//数据库存的绝对路径
}else{
$this->ajaxReturn(['info'=>'非法请求','status'=>0]);
}
}