PHP下载服务器上的文件,可以通过自定义函数方法downtemplateAction()来实现下载,在其方法体内有判断文件是否存在以及是否成功下载、关闭文件等功能。
相关推荐:《php教程》
具体示例如下:/**
* @todo 下载文件
*/
public function downtemplateAction(){
header("Content-type:text/html;charset=utf-8");
$file_name = "template.xlsx";
$file_name = iconv("utf-8","gb2312",$file_name);
$file_sub_path = APP_PATH.'/data/obj/2018-03-21/';
$file_path=$file_sub_path.$file_name;
if(!file_exists($file_path))
{
echo "下载文件不存在!";
exit;
}
$fp=fopen($file_path,"r");
$file_size=filesize($file_path);
//下载文件需要用到的头
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:".$file_size);
Header("Content-Disposition: attachment; filename=".$file_name);
$buffer=1024;
$file_count=0;
while(!feof($fp) && $file_count
{
$file_con=fread($fp,$buffer);
$file_count+=$buffer;
echo $file_con;
}
fclose($fp); //关闭这个打开的文件
}