Laravel8导出excel返回值的简单想法

最近在使用Maatwebsite\Excel扩展进行excel的导出功能,具体怎么操作,这里不详细说了,通过下面代码导出:

//导出excel【$head是excel表头,$list是数据】
return Excel::download(new CustomerExport($head, $list), date('YmdHis') . '.xls');

我本着好奇打印这个返回值:

print_r(Excel::download(new CustomerExport($head, $list), date('YmdHis') . '.xls'));

结果如下:

Symfony\Component\HttpFoundation\BinaryFileResponse Object
(
    [file:protected] => Symfony\Component\HttpFoundation\File\File Object
        (
            [pathName:SplFileInfo:private] => /home/vagrant/www/admin/storage/framework/cache/laravel-excel/laravel-excel-4U89uL9YLn4vNb1QrCDelsmv4Yrk3Ff.xls
            [fileName:SplFileInfo:private] => laravel-excel-4U89uL9YLn4vNb1QrCDelsmv4Yrk3Ff.xls
        )

    [offset:protected] => 0
    [maxlen:protected] => -1
    [deleteFileAfterSend:protected] => 1
    [headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
        (
            [computedCacheControl:protected] => Array
                (
                    [public] => 1
                )

            [cookies:protected] => Array
                (
                )

            [headerNames:protected] => Array
                (
                    [cache-control] => Cache-Control
                    [date] => Date
                    [last-modified] => Last-Modified
                    [content-disposition] => Content-Disposition
                )

            [headers:protected] => Array
                (
                    [cache-control] => Array
                        (
                            [0] => public
                        )

                    [date] => Array
                        (
                            [0] => Thu, 08 Dec 2022 05:57:26 GMT
                        )

                    [last-modified] => Array
                        (
                            [0] => Thu, 08 Dec 2022 07:16:21 GMT
                        )

                    [content-disposition] => Array
                        (
                            [0] => attachment; filename=20221208152026.xls
                        )

                )

            [cacheControl:protected] => Array
                (
                    [public] => 1
                )

        )

    [content:protected] => 
    [version:protected] => 1.0
    [statusCode:protected] => 200
    [statusText:protected] => OK
    [charset:protected] => 
)

很明显他是个对象。

因为我是前后端分离的,接口也是直接上面代码的,前端同学使用a标签跳到接口地址进行下载的,可以成功。但是打开F12的network查看返回值,前端拿到的是文件流,如下:

Laravel8导出excel返回值的简单想法

为什么直接运行接口返回的是个对象,前端拿到居然变为文件流了?

原来是返回的时候,自动给返回头加了两个参数

Content-Disposition:attachment; filename=20221208152026.xls
Content-Type:application/vnd.ms-excel

Content-Disposition不就是对象里面的头消息嘛

Laravel8导出excel返回值的简单想法

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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