在 Laravel 中下载后如何重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25624927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I redirect after download in Laravel?
提问by Lucas Campos
I'm using maatwebsite/excel library to create excel files then download my file
我正在使用 maatwebsite/excel 库来创建 excel 文件然后下载我的文件
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!']);
}
}
that is my function to generate excel file :
这是我生成excel文件的功能:
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');
}
but after I download the excel file I cant redirect to a route or view and I Also tried to use :
但在我下载 excel 文件后,我无法重定向到路由或视图,我也尝试使用:
routes:
路线:
Route::post('relatorios/todas', array('as' => 'relatorios.todas', 'after' => 'voltar', 'uses' => 'ReportsController@todas'));
filter:
筛选:
Route::filter('voltar', function()
{
return Redirect::back()->with('message', '<p class="bg-success"><b>Relatório gerado com sucesso</b></p>');
});
but didnt work anyway, have another way to redirect after download my file ??!
但无论如何都不起作用,下载我的文件后还有另一种重定向方式吗??!
thx in advance!
提前谢谢!
回答by Antonio Carlos Ribeiro
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]
- 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>
Also, take a look at this answer: PHP generate file for download then redirect
回答by Lucas Campos
that worked
那有效
I gave up from using ajax and just tried with routes
我放弃使用 ajax 并尝试使用路由
Route::get('relatorios/exportar/{cod}', array('as' => 'relatorios.exportar', 'uses' => 'ReportsController@exportar'));
my controller
我的控制器
public function exportar($cod)
{
set_time_limit(0);
$datainicio = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_inicio');
$datafinal = DB::table('tb_periodo')->where('cod', $cod)->pluck('periodo_fim');
$mes = DB::table('tb_periodo')->where('cod', $cod)->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);
$nome = 'Marca??es'.$mes.'-'.Carbon::now()->year;
$this->horario->allToExcel($nome, $horarios);
}
view:
看法:
{{ link_to_route('relatorios.exportar', 'Exportar para excel', array($cod), array('class' => 'btn btn-success')) }}
that's solved for me, because dont load another page and download the correct file. thx for the help!!
这对我来说已经解决了,因为不要加载另一个页面并下载正确的文件。谢谢你的帮助!!