问题
I am trying to export and download some data in a csv file using an ajax request. I was able to output the data in a json response to test but could not get it to download in a data.csv file
Following is the code I have written so far
public function download(Request $request)
{
if(!empty($request->input('my_checkbox')))
{
$studentIdToExportArray = $request->input('my_checkbox');
//$msg = is_array($studentIdToExportArray);//returns true
$selectedStudents = [];
foreach($studentIdToExportArray as $student_id)
{
$student = Students::find($student_id);
array_push($selectedStudents, $student);
}
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output=fopen("php://output","w");
fputcsv($output,array("ID","firstname","surname","email","nationality","address_id","course_id"));
foreach($selectedStudents as $s1)
{
$array = json_decode(json_encode($s1), true);
fputcsv($output, $array);
}
fclose($output);
return response()->json([
'test'=> $selectedStudents
]);
}
}
Screenshot of output response in console
Problem: The file data.csv does not download
回答1:
Try:
$file=fopen('../storage/app/test.csv','w');
$headers = array(
'Content-Type' => 'text/csv',
);
$path = storage_path('test.csv');
return response()->download($path, 'test.csv', $headers);
回答2:
You first have to save the file to a location on your local or a cloud disk and then do a file response or a download response. These are the download options like shown in the docs: https://laravel.com/docs/5.5/responses#file-responses
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
return response()->download($pathToFile)->deleteFileAfterSend(true)
ps: you can also look at using a dedicated package for this, or just use the package as a reference. https://github.com/Maatwebsite/Laravel-Excel
来源:https://stackoverflow.com/questions/48802700/exporting-csv-response-laravel-5-5-and-download-as-csv-file