2016-12-20 101 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