search

Home  >  Q&A  >  body text

In Laravel, how to display image files stored in the storage directory.

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?

滿天的星座滿天的星座2753 days ago600

reply all(1)I'll reply

  • 滿天的星座

    滿天的星座2017-05-16 16:50:12

    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.

    reply
    0
  • Cancelreply