我正试图让我的Laravel应用程序下载一个excel文件,其中包含phpSpreadSheet个PhpExcel的续集.但到目前为止,我没有任何运气.我第一次try 通过onClick调用Axios,但没有成功,因为JS不允许保存东西.在那之后,我试图将按钮连接到一个Laravel动作,但这只是打开了一个空白页面.
我不知道这里是否有人能帮助我,但我仍然充满希望
我正试图让我的Laravel应用程序下载一个excel文件,其中包含phpSpreadSheet个PhpExcel的续集.但到目前为止,我没有任何运气.我第一次try 通过onClick调用Axios,但没有成功,因为JS不允许保存东西.在那之后,我试图将按钮连接到一个Laravel动作,但这只是打开了一个空白页面.
我不知道这里是否有人能帮助我,但我仍然充满希望
首先,您需要在路由中设置一个端点,以便使用ajax(在您的例子中是axios)调用它:
Route::get('spreadsheet/download',[
'as' => 'spreadsheet.download',
'uses' => 'SpreadsheetController@download'
]);
在控制器中:
public function download ()
{
$fileContents = Storage::disk('local')->get($pathToTheFile);
$response = Response::make($fileContents, 200);
$response->header('Content-Type', Storage::disk('local')->mimeType($pathToTheFile));
return $response;
}
In case you don't have the file you can save it to php://output:
public function download ()
{
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="file.xlsx"');
$writer->save("php://output");
}
现在你只需要调用端点/spreadsheet/download
就可以开始下载了,但是普通的<a href="/spreadsheet/download">Download</a>
就可以了.
Hope this helps you.