【问题标题】:Laravel AccessDeniedException with file download response带有文件下载响应的 Laravel AccessDeniedException
【发布时间】:2019-10-10 15:23:26
【问题描述】:

在我的 Laravel 脚本中,我将文本写入使用 tmpfile() 创建的文件,然后尝试返回文件下载响应,以便用户下载该文件。

$file = tmpfile();
fwrite($file, 'Write some text to the file.');
return Response::download(stream_get_meta_data($file)['uri'], 'myFile.txt');

结果是AccessDeniedException 说:

The file /tmp/phpJfvGtH could not be accessed

如果我不使用 Laravel 的 Response 类强制文件下载响应,它可以正常工作:

header('Content-disposition: attachment; filename=myFile.txt');
header('Content-type: text/plain');
readfile(stream_get_meta_data($file)['uri']);

为什么这行得通,但使用Response::download() 方法却不行?

我正在使用Laravel Framework version 4.2.16

【问题讨论】:

  • 在您的退货声明之前,var_export(is_readable(stream_get_meta_data($file)['uri'])); 显示什么?
  • 它返回true。由于is_readable($path) 返回false,文件/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/File/MimeType/MimeTypeGuesser.php 抛出异常,这似乎与var_export(is_readable(stream_get_meta_data($file)['uri'])); 返回true 相矛盾。我很困惑。
  • 我是这么认为的。这就是我询问 is_readable 的原因。 $splFile = new Symfony\Component\HttpFoundation\File\File((string)stream_get_meta_data($file)['uri'])); var_export($splFile->isReadable()); var_export(is_readable($splFile->getPathname())); var_export(posix_getuid()); var_export(posix_geteuid()); 怎么样

标签: php symfony laravel-4


【解决方案1】:

发生这种情况是因为对文件资源的所有引用都丢失了。根据tmpfile() 文档:

文件在关闭时自动删除(例如,通过调用 fclose(),或者没有对 tmpfile() 返回的文件句柄的剩余引用),或者脚本结束时。

在您的情况下,当您将文件路径传递给 download() 函数而不是处理程序本身时,您对文件处理程序 $file 的唯一引用留在当前范围内。

return Response::download(stream_get_meta_data($file)['uri'], 'myFile.txt');

那么,解决方案呢:

  1. 您可以通过流式传输临时文件的内容(即Response::stream())自己处理文件响应
  2. 或者以某种方式确保对文件句柄的引用不会丢失。我通过将文件处理程序传递给标题选项进行了一些虚拟检查,它起作用了。
    (不确定它将来是否会破坏任何东西,因为标题选项不是为这样的事情设计的)

    $file = tmpfile();
    fwrite($file, 'Write some text to the file.');
    return Response::download(stream_get_meta_data($file)['uri'], 'myFile.txt', [
        $file,
    ]);
    
  3. 或者不创建临时文件,而是在存储文件夹中创建文件。并考虑一下临时文件的清理机制

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    相关资源
    最近更新 更多