Heim  >  Artikel  >  Backend-Entwicklung  >  PHP实现下载文件功能

PHP实现下载文件功能

WBOY
WBOYOriginal
2016-08-08 09:19:30823Durchsuche

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教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:从Wordpress转五指CMSNächster Artikel:php异常、错误处理机制