2016-12-20 170 views
1

在我的Laravel 5.3中,我上傳了文件到「uploads/files/file.pdf」。當我嘗試下載它時,使用「file_exists」功能找到該文件,但沒有彈出窗口將文件保存到本地計算機中。注意:我通過將文件移動到名爲「local」的子目錄從URL中刪除了「public」文件夾。Laravel 5:下載文件不顯示彈出保存

請指教有什麼問題。

namespace App\Http\Controllers; 

use Auth; 
use Illuminate\Http\Request; 
use App\Http\Requests; 
use Response; 

............................... 

public function getDownload() 
{ 
    $file= "uploads/files/file.pdf"; 

    echo $file; 

    if(file_exists($file)){ 
     dd('File is exists.'); 
    }else{ 
     dd('File is not exists.'); 
    }   

    $headers = array('Content-Type: application/pdf',); 
    return Response::download($file, 'filename.pdf', $headers); 
} 
+0

一次清除瀏覽器緩存並重試 –

+0

嘗試'$ file = public_path()。 「/uploads/files/file.pdf」;' –

回答

0

我想你需要一個頭來告訴瀏覽器打開文件或下載它。

所以下載它在瀏覽器中使用

header('Content-Disposition: attachment; filename="filename.pdf"'); 

要在瀏覽器使用

header("Content-Disposition: inline; filename=filename.pdf"); 

在您的例子打開它,你應該有你的$header可變像

$headers = array('Content-Type: application/pdf','Content-Disposition: inline; filename=filename.pdf'); 

$headers = array('Content-Type: application/pdf','Content-Disposition: attachment; filename="filename.pdf"'); 

我個人使用它像下面

header("Content-type: application/pdf"); 
header("Content-Length:" . strlen($file)); 
//header("Content-Disposition: inline; filename=file.pdf"); 
header('Content-Disposition: attachment; filename="file.pdf"'); 
print $file; 

或者,也許只是在你的情況下做到這一點像下面

return response()->download("uploads/files/file.pdf"); 

整個控制器代碼如下

namespace App\Http\Controllers; 

use Auth; 
use Illuminate\Http\Request; 
use App\Http\Requests; 
use Response; 

............................... 

public function getDownload() 
{ 
    $file= "uploads/files/file.pdf"; 

    //echo $file; 

    if(file_exists($file)){ 
     //dd('File is exists.'); 
     return response()->download($file); 

    }else{ 
     //dd('File is not exists.'); 
     abort(404); 
    } 
} 
+0

我使用它們中的每一個,但它仍然不起作用。 $ headers = array('Content-Type:application/pdf','Content-Disposition:attachment; filename =「filename.pdf''); return Response :: download($ file,'filename.pdf',$ headers); – Naren

+0

@Naren I'v更新了我的答案,我是如何做到的。你有沒有嘗試可能只是'返回響應() - >下載($ pathToFile);'或'返回響應() - >下載($ pathToFile,$ name,$ headers);' – KuKeC

+0

仍然無法正常工作。你能寫出完整的控制器和功能嗎? – Naren