【问题标题】:laravel store files and access themlaravel 存储文件并访问它们
【发布时间】:2023-03-12 23:36:05
【问题描述】:

我使用此代码存储文件:

 $files = $request->file('files');
    if($request->hasFile('files'))
    {
        foreach($files as $file)
        {
            $file->store('files'));
        }
    }

本示例中的文件保存在storage/app/files/ 下,这很好,因为它们因此不能公开访问(它们也不应该公开访问)。但是,如果我想为我的用户提供这些文件的下载选项,我将如何访问它们?我想到了 PHP 读取文件并将其“呈现”给用户。但是,我是 laravel 的新手,在这一点上有点迷茫。

有什么想法吗?

【问题讨论】:

  • 谢谢,这看起来不错。现在应该在我的网页中显示的图像文件(例如个人资料图片)怎么样?
  • 这是文件响应的情况(在您的答案下方的文档中的一个选项卡中涵盖)@apokryfos?
  • 是的,这就是您用于“内联”文件响应的内容

标签: php laravel storage


【解决方案1】:

将文件作为响应发送的主要方式有 3 种:

文件下载(使用内容配置:附件)

return response()->download(storage_path("app/files/filename.ext")); //Where filename.ext is the file you want to send

内联文件(使用内容配置:内联)

return response()->file(storage_path("app/files/filename.ext"));

对于非常大的文件,也可以使用Symfony's streamed response

【讨论】:

  • 这看起来不错。但是,我现在如何(使用“内联文件”)将我的图像呈现为 HTML?通常,我通过 HTML 属性设置图像源:<img src=...>
  • @John 你可以设置src=/route/that/sends/the/file/response/(或者更好的(src="{{url('route/that/sends/the/file/response')}}"
  • 好吧,这就是我的想法,但不确定在 laravel 中是否有更简单的方法。
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2016-11-11
  • 2018-12-19
  • 2020-04-26
  • 2020-11-10
相关资源
最近更新 更多