2012-11-19 27 views
3

我正在使用最新CI。在当地工作时我没有任何问题。但是当我将我的作品移到服务器上时,我正面临一个问题。Codeigniter - 使用force_download函数下载文件

当我从我的下载选项卡下载文件时,文件正在以正确的大小和格式下载。但是当我打开下载的文件,例如,如果它是一个图像,图像不显示,或者如果它是单词,它要求选择编码类型,并选择编码类型后,内容是垃圾字符。

如何解决这个问题。

在此先感谢。

代码我用来下载文件:

$content = file_get_contents($file_loc); 
force_download(FILENAME.EXT, $content); 
+1

邮政编码在这里。 –

+0

在问题底部添加了代码 – Shankar

+0

这听起来像是一个Web服务器配置问题......你在本地运行什么Web服务器? – Malachi

回答

2

试试这个代码如下:

<?php 

function downloadFile($file){ 
    $file_name = $file; 
    $mime = 'application/force-download'; 
    header('Pragma: public');  
    header('Expires: 0');   
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Cache-Control: private',false); 
    header('Content-Type: '.$mime); 
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Connection: close'); 
    readfile($file_name);  
    exit(); 
} 
?> 

,并调用功能:提供的文件 “image.jpg的”

<?php 
downloadFile("./files/image.jpg"); 
?> 

是正确的地址

+0

否。它不起作用。它下载后再次显示相同的错误。 最后,我决定给该文件的完整网址的链接。 – Shankar

+0

我试过把它放进帮手中。然后在控制器中调用该函数并且它工作。不要忘记加载帮手。 –

0

如果您愿意,您可以试试这个:

function download() 
{ 
    // asumming you have http://www.domain.com/index.php/controller/download/file_name/extension/ 
    $extension = $this->uri->segment(4); // file extension 
    $file_name = $this->uri->segment(3) . '.' . $extension; // file name 
    $file_path = FCPATH . 'application/documentos/' . $file_name; // absolute path to file 
    if (is_file($file_path)) { 
     $mime = 'application/force-download'; 
     header('Pragma: public');  
     header('Expires: 0');   
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
     header('Cache-Control: private',false); 
     header('Content-Type: ' . $mime); 
     header('Content-Disposition: attachment; filename="' . $file_name . '"'); file name 
     header('Content-Transfer-Encoding: binary'); 
     header('Connection: close'); 
     readfile(base_url() . 'application/documentos/' . $file_name); // relative path to file 
     exit(); 
    } else { 
     redirect('/welcome/'); 
    } 
} 
+0

不要尝试重写自己的下载助手,除非当前的不适合你 – larrytech

0

Add ob_clean();之前的代码force_download();否则图像,文件文件被损坏。

ob_clean(); 
$content = file_get_contents($file_loc); 
force_download(FILENAME.EXT, $content); 
3

这对我有用。

ob_clean(); 
$data = file_get_contents("localhost/qlip/uploads/filename.jpg"); //assuming my file is on localhost 
$name = 'document.jpg'; 
force_download($name,$data); 
0
在CI 3

:对我的作品

$data = 'Here is some text!'; 
$name = 'mytext.txt'; 
force_download($name, $data); 

或:

// Contents of photo.jpg will be automatically read 
force_download('/path/to/photo.jpg', NULL); 

source

0

你的文件路径不正确。修复路径来纠正和run.it应该工作。