thinkphp 文件下载

//ajax执行程序判断 下载
public function downloads_resources()
{
$resources = M("resources");
$id = $this->_request("id");

$dataInfo = $resources->find($id);
if(!$dataInfo){
$this->ajaxReturn("","下载资源文件不存在",2);
}


$file = $dataInfo['resource_path'];
        $file_path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.$file;


        if (!file_exists($file_path)){
        header("Content-type: text/html; charset=utf-8");
$this->ajaxReturn("","下载资源文件不存在!",2);
        exit;
        } else {
//$this->download($file_dir,iconv('utf-8','gbk', $dataInfo['resources_name'].'_'.date('Y_m_d_H_i_s',time())));
$this->ajaxReturn("","下载资源文件存在!",1);
        }
    }


public function downloads() 

$resources = M("resources");
$id = $this->_request("id");
$dataInfo = $resources->find($id);


//自动增加下载量
$resources->where('id='.$id)->setInc('resource_downloads',1);


$file = $dataInfo['resource_path'];
//绝对路径
        $file_path = $_SERVER['DOCUMENT_ROOT'].__ROOT__.$file;
//去掉路径中多余的空格
$file_path = trim($file_path); 
//判断要下载的文件是否存在
$file_path = str_replace('\\','/',$file_path);
//文件名称
$resources_name = explode('.',$dataInfo['resources_name']);
$file_name = iconv('utf-8','gbk', $resources_name[0].'_'.date('Y_m_d_H_i_s',time()));
/* if(stripos($_SERVER["HTTP_USER_AGENT"],"firefox")){
$file_name = urldecode($file_name);
}else{
$file_name = urlencode($file_name);
}
*/ $file_size = filesize($file_path); 
$fp = fopen($file_path,"r"); 
// 设置下载速率(=> 512 kb/s)
$download_rate = 512;
//$buffer_size = 1024*1024*1024*10; 
$cur_pos = 0; 

$extype = pathinfo($file_path, PATHINFO_EXTENSION);
header("Content-type: application/octet-stream;charset=utf-8"); 
header("Accept-Ranges: bytes"); 
header("Accept-Length: $file_size"); 
header("Content-Disposition: attachment; filename=".$file_name.'.'.$extype); 

while(!feof($fp)&&$file_size-$cur_pos>$buffer_size) 

//$buffer = fread($fp,$buffer_size);
$buffer = fread($fp, round($download_rate*1024));
echo $buffer; 
$cur_pos += $buffer_size; 



$buffer = fread($fp,$file_size-$cur_pos); 
echo $buffer; 
fclose($fp); 
return true; 
 
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值