下载(大)文件:简单重定向与下载帮助程序

时间:2012-07-12 12:36:54

标签: codeigniter

我对制作下载系统有疑问。我过去做了一个,但它非常基本。我所做的是将下载的文件名添加到数据库中:

id | title     | filename
---|-----------|--------------
 1 | Something | something.zip

然后当用户访问download.php?id = 1时,他将被简单地重定向到: /path/to/downloads/something.zip 使用:

header('Location: /path/to/downloads/something.zip');

这会使浏览器自动开始下载。但这样做可以吗?我正在使用Codeigniter构建一个下载系统,并且有一个可用的下载助手。要提供下载,我需要:

$data = file_get_contents('/path/to/downloads/something.zip');
$name = 'Something';

force_download($name, $data);

我注意到,与简单重定向相比,由于file_get_contents(),下载速度较慢。我有一些大的下载量(最大1 GB)。你有什么建议?我应该使用Codeigniter下载帮助程序,直接使用重定向到文件或其他东西吗?

1 个答案:

答案 0 :(得分:1)

取自php.net

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'); 

}