laravel-admin 使用laravels时,excel导出异常的问题

预处理

新建自定义异常类

<?php
namespace App\Exceptions;
use Throwable;
use Exception;

class SwooleExitException extends Exception
{
    protected $response;
    public function __construct($response,$message = "", $code = 0, Throwable $previous = null)
    {
        $this->response = $response;
        parent::__construct($message, $code, $previous);
    }
    //获取响应内容
    public function getResponse(){
        return $this->response;
    }
}

在Handler.php中,render方法中添加代码


protected $dontReport = [
    //
    SwooleExitException::class
];

public function render($request, Exception $exception)
{

    if ($exception instanceof SwooleExitException) {
        //直接调用perpare
        return $exception->getResponse()->prepare($request);
    }

}

swoole_exit 为自定义的全局函数

if (!function_exists('swoole_exit')){
    function swoole_exit($response)
    {
        throw new App\Exceptions\SwooleExitException($response);
    }
}

接下来是改框架。小弟不才。没有想到其他办法。希望各位大神指点迷津。

小弟qq247552748

第一步

修改Encore\Admin\Grid\Exporters\CsvExporter.php 文件

public function export()
{
    .....
    ....

    response()->stream($response, 200, $this->getHeaders())->send();

    exit;
}

处理掉exit

改为

public function export()
{
    .....
    ....

   swoole_exit(response()->stream($response, 200, $this->getHeaders()));
}

第二步

Encore\Admin\Middleware\Pjax.php

跟第一步同样道理,处理掉exit方式,修改为请求返回的形式

public static function respond(Response $response)
    {
        $next = function () use ($response) {
            return $response;
        };
        swoole_exit((new static())->handle(Request::capture(), $next));

//        (new static())->handle(Request::capture(), $next)->send();

//        exit;
    }

第三步

Encore\Admin\Grid\Exporters\ExcelExporter

public function export()
{
//        $this->download($this->fileName)->prepare(request())->send();

        swoole_exit($this->download($this->fileName)->prepare(request()));
//        exit;
}

参考自 博客:Laravel-admin 在 Laravels 运行的的一些问题解析——记一次因为莽而付...

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 2
德国科隆街头的大胡子

小弟不才,已看迷津,有请楼下解决

3年前 评论
妖都水鬼 (楼主) 3年前
陈先生

在我的印象里面 swoole 不支持返回文件流格式吧....

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!