简体   繁体   中英

Return file download from storage in Laravel

I'd like to be able to retrieve a file from storage in my controller.

public function getFile($fileID) {
    $file = CommUploads::where('id', $fileID)->first();

    if (Auth::user()->id == $file->user_id || Auth::user()->id == $file->artist_id) {
        $fileGet = Storage::get($file->file_path);
        return $fileGet;
    }
}

Now, I'm able to get the path correctly, however, all that comes out is gibberish, as if you're looking at an image without the extension.

Ideally I'd like this to work as a "save as" sort of thing.

How can I do this?

You should use a file download response .

public function getFile($fileID) {
    $file = CommUploads::where('id', $fileID)->first();

    if (Auth::user()->id == $file->user_id || Auth::user()->id == $file->artist_id) {
        return response()->download(storage_path('app/' . $file->file_path));
    }
}

It's bad practice to return just a string. When using Laravel responses , Laravel makes sure the headers and other requirements are set correctly to return the response to the browser.

You can use method download instead of get on Storage facade.

public function getFile($fileID) {
    $file = CommUploads::where('id', $fileID)->first();

    if (Auth::user()->id == $file->user_id || Auth::user()->id == $file->artist_id) {
        return Storage::download($file->file_path);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM