【问题标题】:File download not working in Laravel 5?文件下载在 Laravel 5 中不起作用?
【发布时间】:2018-01-20 05:39:27
【问题描述】:

我在/public/storage/attachment 中存储了一个文件,该文件有一个hashname,它也存储在我的数据库中以及attachmentsfilehashname 列中

public/attachment/N52lbwmzubAcgUfHYhCC4A6NFBniIVmK.pdf

在视图中,我将文件显示为链接,这样当用户单击链接时,文件就会被下载。

<a href="{{ URL::to( '/download/'.$post->attachments[0]->filehashname) }}">
   {{ $post->attachments[0]->filename }}
</a>

web.php

Route::get('/download/{filehashname}', 'PostController@downloadAttachment');

后控制器

public function downloadAttachment($filehashname)
    {
        $file= public_path('/storage/attachment/'.$filehashname);

        return response()->download($file, 'demo.pdf');
    }

但这不会下载文件它打开 URL http://localhost:8000/download/public/attachment/N52lbwmzubAcgUfHYhCC4A6NFBniIVmKfctqMNOq.pdfPage Not Found

如果我硬编码文件名并单击链接,则它会下载,但在 url 中动态传递文件名会导致页面未找到错误。

如何解决?

【问题讨论】:

  • 文件是否退出文件夹?
  • 是的,确实如此。当我将名为 abc.pdf 的文件存储在文件夹中并直接在控制器中将路径作为 $file= public_path('/storage/attachment/abc.pdf');但是当我在 URL 中传递文件名时它不起作用
  • 您的文件是保存在公用文件夹还是存储文件夹?

标签: php laravel file laravel-5 download


【解决方案1】:

如果您的文件存储在公共目录中,请尝试 public_path(),如果您的文件保存在存储目录中,请尝试 storage_path()

$destination = storage_path('storage/attachment/'); // if your storage folder contains only attachement folder then like this :- storage_path('attachment/');
               or
$destination = public_path('storage/attachment/');
$pathToFile = $destination.$filehashname;
return response()->download($pathToFile,'demo.pdf');

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    你只需要在锚标签中添加downlaod选项

    <a href="{{ URL::to( '/download/'.$post->attachments[0]->filehashname) }}" download >
     {{ $post->attachments[0]->filename }}
    </a>
    

    正在回答here

    【讨论】:

      【解决方案3】:

      试试这个

      $myFile = public_path($filehashname); # place file in public/ and check this; 
      # If works add this public_path("storage/attachment/".$filehashname);
      $headers = ['Content-Type: application/pdf'];
      $newName = "demo.pdf";
      return response()->download($myFile, $newName, $headers);
      

      public_path()

      【讨论】:

        猜你喜欢
        • 2017-08-08
        • 2017-10-19
        • 2016-05-26
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多