2013-02-12 68 views
9

通过阅读codeigniter文档,我使用以下代码从我的服务器强制下载文件。Codeigniter Force下载文件

function download($file_id){ 
     $file = $this->uploadmodel->getById($file_id); //getting all the file details 
                 //for $file_id (all details are stored in DB) 
     $data = file_get_contents($file->full_path); // Read the file's contents 
     $name = $file->file_name;; 

     force_download($name, $data); 
    } 

该代码是工作文件的图像,但是当它与PDF文件的情况下,它不起作用。我没有对所有文件扩展名进行测试,但由于它不适用于PDF,因此它可能不适用于其他各种文件类型。 任何解决方案?

+0

不工作如何?不下载?没有在PDF阅读器中打开?错误? – 2013-02-12 15:16:34

+1

是的..当我碰到我创建'download/32'的链接时,它只是打开链接,它是一个空白页面。 它是'下载/ $ file_id' .. – prakashchhetri 2013-02-12 15:18:15

+0

.zip,.jpg,.txt,.gif所有工作,但不.pdf – prakashchhetri 2013-02-12 15:20:04

回答

19

我有类似的问题,我认为问题在于某些mime和头文件发送到浏览器。我最终使用的代码是http://taggedzi.com/articles/display/forcing-downloads-through-codeigniter。使用下面的函数而不是force_download。迄今为止它已经为我工作。

function _push_file($path, $name) 
{ 
    // make sure it's a file before doing anything! 
    if(is_file($path)) 
    { 
    // required for IE 
    if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } 

    // get the file mime type using the file extension 
    $this->load->helper('file'); 

    $mime = get_mime_by_extension($path); 

    // Build the headers to push out the file properly. 
    header('Pragma: public');  // required 
    header('Expires: 0');   // no cache 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($path)).' GMT'); 
    header('Cache-Control: private',false); 
    header('Content-Type: '.$mime); // Add the mime type from Code igniter. 
    header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name 
    header('Content-Transfer-Encoding: binary'); 
    header('Content-Length: '.filesize($path)); // provide file size 
    header('Connection: close'); 
    readfile($path); // push it out 
    exit(); 
} 

希望它有帮助。

+0

也许这是一个老版本的codeigniter问题,但现在我使用codeigniter 2.2,pdf没有问题, RJ Anoop的回答很有用。 – Musa 2014-10-20 07:37:04

8

它正在为.pdf也!!! plz检查文件的路径。这可能是我想的问题。 我也有这个问题。 但是,当我纠正文件的路径,它的工作完美... 以下是我如何写代码!

if($src == "xyyx") 
{ 
$pth = file_get_contents(base_url()."path/to/the/file.pdf"); 
$nme = "sample_file.pdf"; 
force_download($nme, $pth);  
} 

希望这可能有帮助! 感谢和问候

+0

最初没有工作。只是显示一个空白页面。我同意添加“.pdf”扩展名 – aphoe 2015-03-11 11:46:20