Laravel-文件下载 [英] Laravel - File Downloads

查看:207
本文介绍了Laravel-文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I'm trying to fix a Laravel download bug I am dealing with. I have the correct route setup, and correct function in the controller. I also am able to confirm that I have access to the file because I created a file using the exact same route and returned it. By doing this I was able to successfully return the contents of the file. However when I try and use a button from the view and call the controller function I get this error:

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 ...

现在是导致此错误的代码:

Now here is the code that resulted in this error:

show.blade.php

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

HonoursController.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错误.但是,我的检查没有向我提供任何其他信息.知道发生了什么吗?

What I have been able to surmise is that I am getting a 500 HTTP error. My inspection does not provide me with any other information however. Any idea what is going on?

推荐答案

尝试一下:

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);
}

从文档中

下载方法可用于生成强制执行以下操作的响应: 用户浏览器以指定路径下载文件.

The download method may be used to generate a response that forces the user's browser to download the file at the given path.

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

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

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

这篇关于Laravel-文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆