我正在尝试使用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无法下载
答案 0 :(得分:1)
<强>尝试:强>
$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);
答案 1 :(得分:0)
首先,您必须将文件保存到本地或云盘上的某个位置,然后执行文件响应或下载响应。这些是文档中显示的下载选项: 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