Laravel-文件下载


Laravel - File Downloads

嗨,我正在尝试修复我正在处理的Laravel下载错误。我在控制器中有正确的路线设置和正确的功能。我还能够确认我有权访问该文件,因为我使用完全相同的路由创建了一个文件并返回了它。通过这样做,我能够成功返回文件的内容。然而,当我尝试使用视图中的按钮并调用控制器功能时,我会出现以下错误:

FileNotFoundException in File.php line 37:
The file "The file "2016-04-04_07-21-50 - Pinging host: 192.168.2.1
2016-04-04_07-21-50 - Host 192.168.2.1 is up!
2016-04-04_07-21-50 - Pinging host: 192.168.2.2
2016-04-04_07-21-53 - Pinging host: 192.168.2.3 ...

下面是导致此错误的代码:

show.blade.php

<a class="btn btn-default col-md-12" href="/getDownload/{{ $now }}" role="button">Download Today's Log</a>

荣誉控制器.php

public function getDownload($id)
    {
      $file = File::get("../resources/logs/$id");
      $headers = array(
           'Content-Type: application/octet-stream',
      );
      #return Response::download($file, $id. '.' .$type, $headers); 
      return response()->download($file, $id.'txt', $headers);
    }

我能够推测的是,我得到了一个500 HTTP错误。然而,我的检查并没有为我提供任何其他信息。知道发生了什么事吗?

试试这个:

public function getDownload($id)
{
    // $file = File::get("../resources/logs/$id");
    $headers = array(
       'Content-Type: application/octet-stream',
    );
    #return Response::download($file, $id. '.' .$type, $headers); 
    return response()->download("../resources/logs/$id", $id.'txt', $headers);
}

来自文档:

下载方法可用于生成响应,该响应强制用户的浏览器在给定路径下载文件。

return response()->下载($pathToFile,$name,$headers);

https://laravel.com/docs/5.1/responses#basic-响应

下载方法的第一个参数应该是文件的路径,而不是文件本身。

下载方法可用于生成响应,该响应强制用户的浏览器在给定路径下载文件。。。

来源:https://laravel.com/docs/5.2/responses#file-下载

遵循以下两个步骤:

  1. 使用模型查找文件的详细信息
  2. 使用Laravel-Response在标头的帮助下下载文件

这里Blog是模型,$id是表示文件的主键。存储文件名的表的列名是cover_image,因此$file_name=$blog->cover_image为我们提供文件名。让我们假设我们的文件存在于Laravel的公共文件夹的upload/images/中。

控制器

`public function download(Blog $blog,$id){
    $blog=$blog->find($id);
    $headers = array(
        'Content-Type: application/octet-stream',
     );
    $pathToFile=public_path('upload/images/');
    $file_name=$blog->cover_image;
    $download_name='Download-'.$file_name;
    return response()->download($pathToFile.$file_name, $download_name, $headers);
 }`

路线

`Route::get('{id}/file-download',['as'=>'file-download','uses'=>'BlogsController@download']); ` 

查看

这里,['id'=>1]表示我们要下载主键为1的文件。如果你想下载另一个,只需更改任何n个整数。

`<a class="btn btn-primary" href="{{ route('file-download',['id'=>1]) }}">Download</a>

`