php中使用head进行二进制流输出,让用户下载PDF等附件的方法

来源:互联网 发布:linux删除虚拟网卡 编辑:程序博客网 时间:2024/05/29 03:52


在PHP的手册中,有如下的方法,可以让用户方便的下载pdf或者其他类似的附件形式,不过这里居然涉及到了编码的问题,


是这样的,我要传输一个pdf附件给用户,首先是pdf文件已经存放到服务器上面了,在给文件传输过程中取名的问题,总是


在IE下面到用户端的时候,文件名是乱码,导致了文件类型无法识别,有点奇怪,文件名是UTF-8编码的,比如:“中国人.pdf”,


是从数据库中获取出来的,输出转化为$filename = iconv('utf-8', 'gbk', $filename);,传递到用户端的时候,文件名


就正常了,这个有点稍微有点想不通。


function downloadFile$fullPath ){ 

  


  
// Must be fresh start 
  
if( headers_sent() ) 
    die(
'Headers Sent'); 

  
// Required for some browsers 
  
if(ini_get('zlib.output_compression')) 
    
ini_set('zlib.output_compression''Off'); 

  
// File Exists? 
  
if( file_exists($fullPath) ){ 
    
    
// Parse Info / Get Extension 
    
$fsize filesize($fullPath); 
    
$path_parts pathinfo($fullPath); 
    
$ext strtolower($path_parts["extension"]); 
    
    
// Determine Content Type 
    
switch ($ext) { 
      case 
"pdf"$ctype="application/pdf"; break; 
      case 
"exe"$ctype="application/octet-stream"; break; 
      case 
"zip"$ctype="application/zip"; break; 
      case 
"doc"$ctype="application/msword"; break; 
      case 
"xls"$ctype="application/vnd.ms-excel"; break; 
      case 
"ppt"$ctype="application/vnd.ms-powerpoint"; break; 
      case 
"gif"$ctype="image/gif"; break; 
      case 
"png"$ctype="image/png"; break; 
      case 
"jpeg"
      case 
"jpg"$ctype="image/jpg"; break; 
      default: 
$ctype="application/force-download"
    } 

    
header("Pragma: public"); // required 
    
header("Expires: 0"); 
    
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    
header("Cache-Control: private",false); // required for certain browsers 
    
header("Content-Type: $ctype"); 
    
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" ); 
    
header("Content-Transfer-Encoding: binary"); 
    
header("Content-Length: ".$fsize); 
    
ob_clean(); 
    
flush(); 
    
readfile$fullPath ); 

  } else 
    die(
'File Not Found'); 


原先

原先比如文件名是UTF-8的,我想通过header("Content-Type: $ctype;charset=UTF-8");告诉服务器 采用UTF-8进行输出,


结果文件名还是乱码,下次关注下这个问题的原因。