2017-09-01 104 views
0

我想从浏览器访问pdf文件,该文件位于laravel存储文件夹中。我不希望存储是公开的。如何直接从浏览器访问存储器中的pdf文件?

我不想下载它(我设法做到了这一点)。我只想获得一个获取路线,并在浏览器中显示该文件,如:www.test.com/admin/showPDF/123/123_321.pdf。

123是一个id。

如果我使用:

storage_path('app/'.$type.'/'.$fileName); 
or 
Storage::url('app/'.$type.'/'.$fileName); 

回报的完整服务器路径。

谢谢。

回答

0

您可以从存储文件夹中读取它,然后将内容传送到浏览器并强制浏览器下载它。

$path = storage_path('app/'.$type.'/'.$fileName) 

return Response::make(file_get_contents($path), 200, [ 
    'Content-Type' => 'application/pdf', //Change according to the your file type 
    'Content-Disposition' => 'inline; filename="'.$filename.'"' 
]); 
0

您可以存储/程序/公共和公共/存储之间的symbolink链接,以便您可以访问您的文件,通过运行

php artisan storage:link 

更多信息Here

然后你就可以做出这样的路径来访问文件:所以在这种情况下

Route::get('pdffolder/{filename}', function ($filename) 
{ 
    $path = storage_path('app/public/pdffolder/' . $filename); 

    if (!File::exists($path)) { 
     abort(404); 
    } 

    $file = File::get($path); 
    $type = File::mimeType($path); 

    $response = Response::make($file, 200); 
    $response->header("Content-Type", $type); 

    return $response; 
}); 

,如果你保存的文件名为123.pdf PDF格式的文件夹中storage/app/public/pdffolder

you can access it by http://yourdomain.com/pdffolder/123.pdf 

你必须调整它有点,但我认为这可以帮助你。

0

快速和肮脏,但你想要做的是使用你从控制器方法(或路由封闭,你的电话)响应中抓取的路径。喜欢的东西:

public function sendPdf(Request $request) 
{ 
    // do whatever you need to do here, then 
    ... 
    // send the file to the browser 
    $path = storage_path('app/'.$type.'/'.$fileName); 
    return response()->file($path); 
} 

更多这方面的信息,请参阅https://laravel.com/docs/5.4/responses#file-responses,但是这就是我会去了解它

0

你要流式传输文件的请求。在你的控制器做以下的事情

use Symfony\Component\HttpFoundation\Response; 

... 

function showPdf(Request $request, $type, $fileName) 
{ 
    $content = file_get_contents(storage_path('app/'.$type.'/'.$fileName)); 

    return Response($content, 200, [ 
      'Content-Type' => 'application/pdf', 
      'Content-Disposition' => "inline; filename=\"$fileName\"" 
     ]); 
} 

这将直接流您的PDF

0

增加新路线获得PDF

Route::get('/admin/showPDF/{$type}/{$fileName}','[email protected]'); 

,并在控制器

public function pdf($type,$fileName) 
    { 
     $path = storage_path('app/'.$type.'/'.$fileName); 
     return response()->file($path); 
    } 
相关问题