Laravel 响应文件

以实时响应二维码为例

public function qrcode($activity_id, $invite)
    {   
        //二维码内容
        $activity_url = config('app.activity_url') . '?' . http_build_query(['id' => $activity_id, 'invite' => $invite]);
        //二维码图片文件的二进制数据
        $qrcodeStr = Qrcode::format('png')->size(80)->generate($activity_url);
        //直接响应文件,并设置对应的响应头
        return response($qrcodeStr)->withHeaders([
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Headers' => '*',
            'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,PATCH,OPTIONS',
            'Content-Type' => 'image/png;charset=utf-8',
            'Content-Disposition' => 'inline;filename="' . $invite . '.png"'
        ]);
    }

框架实现原理,如上图所示,使用Symfony 组件响应字符串数据,就相当于原生php的

header(....);//设置文件响应头
echo $bindata;//输出文件的二进制数据字符串