导出 CSV 响应 laravel 5.5 并下载为 csv 文件
Exporting CSV response laravel 5.5 and download as csv file
我正在尝试使用 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 未下载
您必须先将文件保存到本地或云盘的某个位置,然后进行文件响应或下载响应。这些是文档中显示的下载选项:
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
尝试:
$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);
我正在尝试使用 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 未下载
您必须先将文件保存到本地或云盘的某个位置,然后进行文件响应或下载响应。这些是文档中显示的下载选项: 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
尝试:
$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);