返回response()-> download();显示空白页

时间:2019-02-28 10:49:20

标签: laravel-5

我有这个代码

return response()->download(storage_path('app/files/gggusers.xlsx'));
在我的控制器中。它执行时没有任何问题,但是它不会触发浏览器下载excel文件,而是显示空白页面。我肯定文件名和位置正确,因为如果我只是将文件名gggusers.xlsx更改为其他名称或删除文件,Laravel将显示此错误

The file "D:\web\speak\storage\app/files/gggusers.xlsx" does not exist

2 个答案:

答案 0 :(得分:0)

事实证明问题是因为我放了

return response()->download(storage_path('app/files/gggusers.xlsx'));

在另一个函数中,然后从要在route内部加载的函数中调用它,如下所示:

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(){
        $this->download();
    }

    public function download(){
        return response()->download(storage_path('app/files/gggusers.xlsx'));
    }
}

上面的代码将显示空白页。没有错误。调用功能下载没有任何问题,但是之后以某种方式仅显示空白页。

如果我只是输入代码

return response()->download(storage_path('app/files/gggusers.xlsx'));

function index()内部,将下载文件。

如果有人可以向我解释原因,就非常感谢。这是某种错误还是某种原因,它是PHP / Laravel的预期行为。由于这个问题浪费了几个小时。

答案 1 :(得分:0)

我知道这是一个老问题,但是我遇到了同样的问题并解决了。您的问题是您正在从download()返回响应(文件)到调用函数index(),但没有从index()返回任何内容回到浏览器选项卡,因此空白页。

public function download(){
        return response()->download(storage_path('app/files/gggusers.xlsx'));
}

在这里,您正在将下载文件返回到index()函数,但是在index()函数中,您什么都没有返回到浏览器。所以改变这个:

public function index(){
        $this->download();
}

对此:

public function index(){
        return $this->download();
}

将文件按预期返回到浏览器选项卡。

这是正确的方法。