我正在尝试使用 ajax 请求导出和下载 csv 文件中的一些数据。我能够以 json 响应输出数据进行测试,但无法将其下载到 data.csv 文件中
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
]);
}
}
问题:文件 data.csv 无法下载
尝试:
$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);
您首先需要将文件保存到本地或云盘上的某个位置,然后进行文件响应或下载响应。这些是文档中显示的下载选项: 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:您还可以考虑使用专用包来实现此目的,或者仅使用该包作为参考。 https://github.com/Maatwebsite/Laravel-Excel