lundi 6 août 2018

Laravel API : Return a file

I have an app in AngularJs for the frontend and Laravel for the backend, in my frontend I send with a post request some data to my api and I want to return this data into a csv file which automatically download.

So here is what I do on my api :

public function exportToCsv(Request $request)
{
  //$helper = new Helper();
  $csv_data = json_decode($request->getcontent(), true);

$headers = [
  'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
  'Content-type' => 'text/csv',
  'Content-Disposition' => 'attachment; filename=legend.csv',
  'Expires' => '0',
  'Pragma' => 'public'
];

$callback = function () use ($csv_data) {
  $FH = fopen('php://output', 'w');
  foreach ($csv_data as $row) {
    fputcsv($FH, $row);
  }
  fclose($FH);
};

//return Response::stream($callback, 200, $headers);
return response()->download($callback, 200, $headers);

}

I also try with stream instead of download, but for these two solutions it's not working.

The result in my angular app when I console.log is 'undefined' but if I check in the network tab the result is the data needed to create a csvfile (all my variables separated by comma), what I'm doing wrong ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire