thinkphp,下載附件

來源:互聯網
上載者:User

標籤:附件   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,下載附件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.