2012-11-19 28 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應該工作。