PHP实现文件下载
项目操作中不可避免要提供文件的下载,有时候要写一些逻辑判断或者提示啥,那下载的方法就需要做些调整。做个下载文件的集锦:
-
readfile — 输出文件 (手册上有说明:读入一个文件并写入到输出缓冲。)
-
<?php
-
$file = \'monkey.gif\' ;
-
-
if ( file_exists ( $file )) {
- header ( \'Content-Description: File Transfer\' );
- header ( \'Content-Type: application/octet-stream\' );
- header ( \'Content-Disposition: attachment; filename=\' . basename ( $file ));
- header ( \'Content-Transfer-Encoding: binary\' );
- header ( \'Expires: 0\' );
- header ( \'Cache-Control: must-revalidate\' );
- header ( \'Pragma: public\' );
- header ( \'Content-Length: \' . filesize ( $file ));
- ob_clean ();
- flush ();
- readfile ( $file );
-
exit;
- }
-
?>
2.使用js实现文件下载,原理也是通过HTML5 a标签设置download属性就能实现。
-
<a href="./upload/user_excel/20161229.txt" download="20161229.txt"> 下 载 文 件 </a>
封装的方法也就是使用实现上述a标签的click事件。
-
#js通过HTML5 download属性实现下载文件
-
function DownloadFileJs( $dir,$filename ){
-
$url = $dir."/".$filename;
-
$uploadjs = "<script type=\"text/javascript\" >
-
var a = document.createElement(\'a\');
-
var url = \"".$url."\";
-
var filename = \'".$filename."\';
-
a.href = url;
-
a.download = filename;
-
a.click();window.URL.revokeObjectURL(url);
-
console.log(a);
-
</script>";
-
echo ($uploadjs);
-
exit;
-
- }
-
?>
-
调用测试如下:
-
$dir = \'./upload/user_excel\';
-
$filename = \'20161229.txt\';
- DownloadFileJs( $dir, $filename );
个人觉得此种方法比较灵活,当然也是相对而言,比如在进行excel导入,后台在处理数据时需要反馈,弹出提示成功与否,再提供异常记录(或操作记录)的下载文件,使用js就比较易处理这个逻辑,而若使用第一种输出缓冲的方法,PHP语句会优先处理解析,会跳过提示,用户体验就不太好 。此种方法也有缺陷,它需要HTML5的支持,只要不是太过旧的浏览器都是支持的。当然也有其他的js方法下载,以后有机会会补充下去。
3、依据浏览器跳转文件地址,#非文本(txt、js、css、html…)直接可下载文件的特性。
- header("location:.\'./upload/user.xls\'");
-
die;
此方法就比较灵活了,根据经验很容易的选择下载文件的方式。
– 天行健,君子以自强不息!