当前位置:Gxlcms > PHP教程 > PHP实现下载文件功能

PHP实现下载文件功能

时间:2021-07-01 10:21:17 帮助过:60人阅读

PHP实现下载功能的代码,从服务器下载文件到本地:

public function downloadTemplateAction()

{
define('Z_WEB_ROOT','http://'.$_SERVER["SERVER_NAME"]); --------host
$file_name = "template.xlsx";
$file_dir = Z_WEB_ROOT."/SITE/public/template/"; ---------文件所在的目录
$file = @ fopen($file_dir . $file_name,"r");
if (!$file) {
echo "File does not exist.";
} else {
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=" . $file_name);
while (!feof ($file)) {
echo fread($file,50000);
}
fclose ($file);
}

}

详细解释:

Header("Content-type: application/octet-stream")的作用:通过这句代码浏览器就能知道服务端返回的文件形式 。

Header("Content-Disposition: attachment; filename=".$file_name)的作用:告诉浏览器返回的文件的名称 。

fclose($file)可以把缓冲区内最后剩余的数据输出到磁盘文件中,并释放文件指针和有关的缓冲区。

以上就介绍了PHP实现下载文件功能,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

人气教程排行