【问题标题】:Unable to download file from s3 using return response()->download($file);无法使用 return response()->download($file) 从 s3 下载文件;
【发布时间】:2017-10-16 16:46:39
【问题描述】:

我正在将文件上传到s3 我希望它在我的控制器中使用以下代码安全下载,但它不起作用。

我使用的是 Laravel 5.5,文件可见性在 s3 上不公开。

if( Storage::disk('s3')->exists($file_path) ) {
      $file =  Storage::disk('s3')->get($file_path);
      return response()->download($file);
}

abort(404, 'File not found.');

它给了我这个错误

is_file() expects parameter 1 to be a valid path, string given
...
/home/vagrant/spark-etr/vendor/symfony/http-foundation/File/File.php:36
#1 /home/vagrant/spark-etr/vendor/symfony/http-foundation/File/File.php(36): is_file('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...')
#2 /home/vagrant/spark-etr/vendor/symfony/http-foundation/BinaryFileResponse.php(94): Symfony\\Component\\HttpFoundation\\File\\File->__construct('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...')
#3 /home/vagrant/spark-etr/vendor/symfony/http-foundation/BinaryFileResponse.php(53): Symfony\\Component\\HttpFoundation\\BinaryFileResponse->setFile('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...', 'attachment', false, true)
#4 /home/vagrant/spark-etr/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php(125): Symfony\\Component\\HttpFoundation\\BinaryFileResponse->__construct('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...', 200, Array, true, 'attachment')

文件位于s3,因为我在下载前检查是否存在。

更新

转储$file var 会给我这样的二进制文件

请帮忙

【问题讨论】:

  • 调用 dd($file); 会得到什么?
  • 它给了我二进制数据,看起来像文件本身
  • file的内容类型是什么?

标签: php laravel amazon-s3


【解决方案1】:

试试

if( Storage::disk('s3')->exists($file_path) ) {
      $file =  Storage::disk('s3')->get($file_path);

      $headers = [
        'Content-Type' => 'your_content_type', 
        'Content-Description' => 'File Transfer',
        'Content-Disposition' => "attachment; filename={$yourFileName}",
        'filename'=> $yourFileName
     ];

    return response($file, 200, $headers);
}

更新

您可以阅读有关下载large 文件的更多信息 Why don't large files download easily in Laravel?

【讨论】:

  • 这是有效的,但文件大小可以达到 100mb 或更大,是否有效。我担心它会给PHP Fatal error: Allowed memory size of 5242880 bytes exhausted
  • 我不确定你会不会看到 :)
  • @Saqueib 我已经粘贴了一个链接来帮助您处理large 文件
  • 你不需要包含 Content-Length 吗?
【解决方案2】:

自己构建响应:

    $file = ''; // what you got from S3
    $mimeType = 'text/plain'; // or whatever the mime type is
    $fileName = 'example.txt';

    $headers = [
        'Content-type'        => $mimeType,
        'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
        'Content-Length'      => sizeof($file),
    ];

    return response($file, 200, $headers);

...或研究如何下载流。

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2016-01-02
    • 2018-11-17
    • 2014-10-16
    相关资源
    最近更新 更多