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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43676109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:52:22  来源:igfitidea点击:

Return file download from storage in Laravel

phplaravel

提问by Felix Maxime

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?

我怎样才能做到这一点?

采纳答案by Jerodev

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 确保正确设置标头和其他要求以将响应返回给浏览器。