我正在尝试使用 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 无法下载
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)