简体   繁体   English

从 Laravel 中的存储返回文件下载

[英]Return file download from storage in Laravel

I'd like to be able to retrieve a file from storage in my controller.我希望能够从我的 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. 使用Laravel响应时 ,Laravel确保正确设置标头和其他要求以将响应返回给浏览器。

You can use method download instead of get on Storage facade.您可以使用方法download而不是get Storage门面。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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