In Laravel, how to display image files stored in the storage directory.
滿天的星座
滿天的星座 2017-05-16 16:48:12
0
1
593

I mentioned that some pictures and files uploaded by users are saved in the storage directory (for security reasons, we don’t want users to download them at will),

So how should we obtain the path when we need to display the file?

滿天的星座
滿天的星座

reply all(1)
滿天的星座

Two solutions, the first one, PHP reads the file and outputs it, the code in Laravel is roughly as follows

// 控制器
// https://github.com/shellus/shcms/blob/v2.0.0/app/Http/Controllers/FileController.php

class FileController extends Controller
{
    public function show($id){
        return File::findOrFail($id) -> downResponse();
    }
}

// Model
https://github.com/shellus/shcms/blob/v2.0.0/app/File.php

public function downResponse(){
    return new BinaryFileResponse($this -> downToLocal());
}
public function downToLocal(){
    $temp_path = tempnam(sys_get_temp_dir(), $this->id);
    $is_success = file_put_contents($temp_path, \Storage::disk('public')->get($this -> full_path));
    return $temp_path;
}
    

Second, use the Linux ln command to create a storage folder soft link to the public folder, but doing so is no different from directly storing files in public.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template