在 Laravel 中下载后如何重定向?

How do I redirect after download in Laravel?(在 Laravel 中下载后如何重定向?)
本文介绍了在 Laravel 中下载后如何重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 maatwebsite/excel 库创建 excel 文件,然后下载我的文件.

I'm using maatwebsite/excel library to create excel files then download my file.

在我的控制器中,我这样做:

In my controller I do like this:

  public function todas()
    {
        $input = Input::all();

        if(isset($input['todos'])&&($input['todos']!=0))
        {
            set_time_limit(0);
            $datainicio = DB::table('tb_periodo')->where('cod', $input['todos'])->pluck('periodo_inicio'); 
            $datafinal  = DB::table('tb_periodo')->where('cod', $input['todos'])->pluck('periodo_fim');
            $mes  = DB::table('tb_periodo')->where('cod', $input['todos'])->pluck('mes_referencia'); 

            $horarioQuery = $this->horario->with(array('funcionario', 'item_contabil'))
                                 ->whereBetween('data', array($datainicio, $datafinal))
                                 ->whereNull('deleted_at')
                                 ->orderBy('cod_funcionario')
                                 ->orderBy('data', 'ASC')
                                 ->get();

            $horarios = reset($horarioQuery);
            
            $count  = count($horarios);

            if($horarios==null)
                return Redirect::route('relatorios.todas')->withErrors(['não existem marcações para este período']);

            $funcionarios = $this->funcionario->all();

            $datainicio  = Carbon::createFromFormat('Y-m-d H:i:s', $datainicio); 
            $datafinal   = Carbon::createFromFormat('Y-m-d H:i:s', $datafinal);

            $nome = 'Marcações'.$mes.'-'.Carbon::now()->year;
            $this->horario->allToExcel($nome, $horarios);

            return View::make('relatorios.todashow', compact('funcionarios', 'datainicio', 'datafinal', 'horarios', 'count', 'nome'));
        }
        else
        {
            return Redirect::route('relatorios.todas')->withErrors(['Selecione um período!']);
        }
    }

这是我生成excel文件的功能:

That is my function to generate excel file :

public static function allToExcel($nome, $horarios)
    {   
            Excel::create($nome , function ($excel) use ($horarios) {

            $excel->sheet('Marcações', function ($sheet) use ($horarios) {

                $sheet->row(1, array(

                            'Unidade',
                            'Nome',
                            'Função',
                            'Data',
                            'Hora Faturada',
                            'Hora Contratada',
                            'Horas Trabalhadas',
                            'Horas Extras',
                            'Tempo Exposicao',
                            'Atividade',
                            'Item Contabil',
                            'Observacoes'
                        ));

                $sheet->row(1, function($row) {
                    $row->setBackground('#2A8005');
                    $row->setFontColor('#ffffff');
                    $row->setFontWeight('bold');
                });

                $i = 2;
                foreach ($horarios as $horario) {
                        
                        if($horario->funcionario->funcao_qt != null)
                            $funcao = $horario->funcionario->funcao_qt;
                        else   
                            $funcao = $horario->funcionario->funcao_a5;
        
                        $sheet->row($i, array(
                            $horario->unidade,
                            $horario->funcionario->nome,
                            $funcao,
                            $horario->data->format('d/m/Y'),
                            $horario->hora_faturada->format('H:i'),
                            $horario->hora_contratada,
                            $horario->getWorkedHours()->format('H:i'),
                            $horario->getExtraHours()->format('H:i'),
                            $horario->tempo_exposicao ?: "-",
                            $horario->atividade,
                            $horario->item_contabil->CTD_DESC01,
                            $horario->observacoes
                        ));
                        if($i % 2 != 0)
                        {
                        $sheet->row($i, function($row) {
                            $row->setBackground('#D1D1D1');
                            });
                        }    
                
                        $i++;
                    }
            });

            })->download('xls');
    }

但是在我下载 excel 文件后,我无法重定向到路线或视图,我也尝试使用:

But after I download the excel file I cant redirect to a route or view and I Also tried to use:

路线:

Route::post('relatorios/todas', array('as' => 'relatorios.todas', 'after' => 'voltar', 'uses' => 'ReportsController@todas'));

过滤器:

Route::filter('voltar', function()
{
    return Redirect::back()->with('message', '<p class="bg-success"><b>Relatório gerado com sucesso</b></p>');
});

但是还是不行,下载我的文件后有没有其他方法可以重定向?

But it didn't work anyway, is there another way to redirect after downloading my file?

推荐答案

做不到.问题在于,如果您向用户浏览器发送下载指令,实际上您是在发送响应,而您只能返回一个响应.

It cannot be done. The problem is that if you send a download instruction to the user browser, you are, as a matter of fact, sending a response and you can send only one response back.

您可以做的是,首先将您的用户重定向到最终"页面,然后在该页面中开始下载.代码类似于:

What you could do is to, first redirect your user to the "final" page and in that page start the download. The code would be something like:

Session::flash('download.in.the.next.request', 'filetodownload.pdf');

return Redirect::to('/whatever/page');

然后在您的新页面中,您将有一些选项:

Then in your new page you'll have some options:

  • HTML:[meta http-equiv="refresh" content="5;url=http://watever.com/create_csv.php"]
  • Javascript: location.href = 'http://watever.com/create_csv.php';
  • iframe:[iframe src="create_csv.php"][/iframe]

因此您可以在布局中执行以下操作:

So you can in your layout do something like:

<html>
  <head>
      @if(Session::has('download.in.the.next.request'))
         <meta http-equiv="refresh" content="5;url={{ Session::get('download.in.the.next.request') }}">
      @endif
   <head>

   <body>
      ...
   </body>
</html>

另外,看看这个答案:PHP 生成文件下载然后重定向

这篇关于在 Laravel 中下载后如何重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)