我正在嘗試從服務器流式傳輸大型 CSV。我加載一個 JSON 文件,將其轉換為數組,然后將其作為 CSV 進行處理。從前端,我通過單擊按鈕調用以下內容downloadCSVData() { axios({ url: '/downloadCSVData', method: 'GET' }).then((response) => { console.log(response) });}然后這個函數執行以下操作public function downloadCSVData(){ //load JSON file $data = file_get_contents($file_path, true); //Convert file to array $array = json_decode($data, true); $headers = [ 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0' , 'Content-type' => 'text/csv' , 'Content-Disposition' => 'attachment; filename=galleries.csv' , 'Expires' => '0' , 'Pragma' => 'public' ]; $response = new StreamedResponse(function() use($array){ // Open output stream $handle = fopen('php://output', 'w'); // Add CSV headers fputcsv($handle, array_keys($array['element'][0]), ','); foreach ($array['element'] as $key => $row) { fputcsv($handle, $row); } // Close the output stream fclose($handle); }, 200, $headers); return $response->send();}現在在前端,在控制臺中,我可以看到按照需要的方式打印響應。然而,根據我的理解,后端應該觸發要下載的文件,而這并沒有發生。我在這里遺漏了什么,如何將其作為物理文件下載到前端?
下載 CSV 文件的流響應
慕的地8271018
2021-11-19 15:14:06