【问题标题】:can we download any file without saving into the application in laravel 5.4?我们可以下载任何文件而不保存到 laravel 5.4 的应用程序中吗?
【发布时间】:2017-11-04 14:21:12
【问题描述】:

我正在尝试完成一项任务,用户只需选择表单数据并单击提交按钮,然后在获取数据后将从数据库中提取数据,我希望该数据必须插入到 csv 文件中,并且该文件必须直接下载到用户的浏览器中,而无需将该文件存储到应用程序的任何位置。 在 laravel 中是否可以将 csv 文件直接下载到用户的浏览器而不存储到应用程序路径中?

我的表格是:

<form id="statistics" method="post" action="{{ action('MyController@store') }}"">
 <div class="form-group">
  <label><input type="checkbox" value="option1" name="option1">option1</label>
 </div>
 <div class="form-group">
  <label><input type="checkbox" value="option2" name="option2">option2</label>
 </div>
 <div class="form-group">
    <button type="submit" id="process" class="btn btn-primary submit">Run Report</button>
 </div>
</form>

MyController/store 方法:

public function store(Request $request) {
  $results = DB::table('table1')
               ->leftjoin('table2 AS s')
               ->get()->toArray();
  $count = count($results);
  if($count > 0)
  {
    $CsvData=array('column1,column2,column3');          
    foreach($results as $value){              
      $CsvData[]=$value->column1.','.$value->column2.', '.$value->column3;
    }
    $filename = 'file_name.csv';
    $file_path=base_path().'/'.$filename; 
    $file = fopen($file_path,"w+");
    foreach ($CsvData as $exp_data){
       fputcsv($file,explode(',',$exp_data));
    }   
    fclose($file);
    $headers = ['Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
                    'Content-Type' => 'application/csv',
                    'Content-Disposition' => 'attachment; filename='.$filename,
                    'Content-transfer-encoding: binary\n'];
    return Response::download($file_path, $filename, $headers);
  }
}

【问题讨论】:

标签: file csv download laravel-5.4


【解决方案1】:

是的,您可以在创建 csv 文件内容后使用正确的标题作为 content-type:attachment 回显它。

header('内容类型:文本/csv'); header('Content-Disposition: attachment; filename="pedidos.csv"');

回声 $shtml;

【讨论】:

  • 感谢您的快速回复。当我更新我的代码时,请再次阅读我的问题。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多