PHP实现文件下载

PHP实现文件下载

项目操作中不可避免要提供文件的下载,有时候要写一些逻辑判断或者提示啥,那下载的方法就需要做些调整。做个下载文件的集锦:

  1. readfile — 输出文件 (手册上有说明:读入一个文件并写入到输出缓冲。)

  1. <?php 
  2. $file = 'monkey.gif'
  3.  
  4. if ( file_exists ( $file )) { 
  5. header ( 'Content-Description: File Transfer' ); 
  6. header ( 'Content-Type: application/octet-stream' ); 
  7. header ( 'Content-Disposition: attachment; filename=' . basename ( $file )); 
  8. header ( 'Content-Transfer-Encoding: binary' ); 
  9. header ( 'Expires: 0' ); 
  10. header ( 'Cache-Control: must-revalidate' ); 
  11. header ( 'Pragma: public' ); 
  12. header ( 'Content-Length: ' . filesize ( $file )); 
  13. ob_clean (); 
  14. flush (); 
  15. readfile ( $file ); 
  16. exit

  17. ?>  

2.使用js实现文件下载,原理也是通过HTML5 a标签设置download属性就能实现。

  1. <a href="./upload/user_excel/20161229.txt" download="20161229.txt"> 下 载 文 件 </a>  

封装的方法也就是使用实现上述a标签的click事件。

  1. #js通过HTML5 download属性实现下载文件 
  2. function DownloadFileJs( $dir,$filename )
  3. $url = $dir."/".$filename;  
  4. $uploadjs = "<script type="text/javascript" > 
  5. var a = document.createElement('a'); 
  6. var url = "".$url.""; 
  7. var filename = '".$filename."'; 
  8. a.href = url; 
  9. a.download = filename; 
  10. a.click();window.URL.revokeObjectURL(url); 
  11. console.log(a); 
  12. </script>"
  13. echo ($uploadjs);  
  14. exit
  15.  

  16. ?> 
  17.  

调用测试如下:

  1. $dir = './upload/user_excel'
  2. $filename = '20161229.txt'
  3. DownloadFileJs( $dir, $filename ); 

个人觉得此种方法比较灵活,当然也是相对而言,比如在进行excel导入,后台在处理数据时需要反馈,弹出提示成功与否,再提供异常记录(或操作记录)的下载文件,使用js就比较易处理这个逻辑,而若使用第一种输出缓冲的方法,PHP语句会优先处理解析,会跳过提示,用户体验就不太好 。此种方法也有缺陷,它需要HTML5的支持,只要不是太过旧的浏览器都是支持的。当然也有其他的js方法下载,以后有机会会补充下去。

3、依据浏览器跳转文件地址,#非文本(txt、js、css、html…)直接可下载文件的特性。

  1. header("location:.'./upload/user.xls'"); 
  2. die

此方法就比较灵活了,根据经验很容易的选择下载文件的方式。

– 天行健,君子以自强不息!

原文地址:https://www.cnblogs.com/followyou/p/6240413.html