標籤:附件 cat strlen 下載檔案 position load php架構 ica import
ThinkPHP架構下有個Org/Net/Http.class.php的方法download。
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]);
}
}
thinkphp,下載附件