我正在使用 spatie 库上传一些文件,这些文件将保存到存储文件夹中。我现在想要完成的是当我是经过身份验证的用户时查看这些文件或图像。我尝试使用此命令创建符号链接,
php artisan storage:link
但这使得这些文件可以公开查看。我只想查看那些文件,只有当用户是经过身份验证的用户时。到目前为止,这就是我所做的,但似乎我错过了一些东西。
路线 :
Route::get('/storage/{filePath}', 'ComplaintsController@fileStorageServe')->where(['filePath' => '.*'])->name('complaints.viewfile');
控制器 :
public function fileStorageServe($file) {
// know you can have a mapping so you dont keep the sme names as in local (you can not precsise the same structor as the storage, you can do anything)
// any permission handling or anything else
// we check for the existing of the file
if (!Storage::disk('local')->exists($filePath)){ // note that disk()->exists() expect a relative path, from your disk root path. so in our example we pass directly the path (/.../laravelProject/storage/app) is the default one (referenced with the helper storage_path('app')
abort('404'); // we redirect to 404 page if it doesn't exist
}
//file exist let serve it
// if there is parameters [you can change the files, depending on them. ex serving different content to different regions, or to mobile and desktop ...etc] // repetitive things can be handled through helpers [make helpers]
return response()->file(storage_path('app'.DIRECTORY_SEPARATOR.($filePath))); // the response()->file() will add the necessary headers in our place (no headers are needed to be provided for images (it's done automatically) expected hearder is of form => ['Content-Type' => 'image/png'];
// big note here don't use Storage::url() // it's not working correctly.
}
看法 :
@foreach($complaint->attachments as $attachment)
<a href="{{url('complaints.viewfile', $attachment->getUrl())}}" target="_blank">{{ $attachment->file_name }}</a>
@endforeach
当我点击链接时,它会给我这样的东西。
http://127.0.0.1:8000/complaints.viewfile/http%3A%2F%2F127.0.0.1%3A8000%2Fstorage%2F3%2F60580fdeadc55_worship.jpg
请帮忙。谢谢...