我正试图让我的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.

Laravel相关问答推荐

密码确认在Livewire中不匹配

如何让 Laravel 的 Collection 表现得像一个流?

使用 laravel 根据当月显示注册用户列表

Laravel 5 如何配置 Queue 数据库驱动程序以连接到非默认数据库?

自定义 Laravel 关系?

Laravel belongsTo 关系 - 试图获取非对象的属性

我的composer 不会完全用 Laravel 4 更新它会被artisan卡住

路由中间的可选参数

你如何找到 Laravel 外观背后的底层类?

Laravel Eloquent:访问属性和动态表名

Laravel 5.5 在迁移文件中设置整数字段的大小

Laravel 生产问题 - 使用 Laravel 4.1.x 更新composer

Laravel 动作未定义

如何在 Laravel 5.1 中为Electron邮件添加标题

laravel 5.1 在没有 VM 重启的情况下看不到作业(job)文件的更改

Select,where JSON 包含数组

如何在 Laravel 5 中的每个相关输入字段旁边显示验证错误?

Laravel 验证存在于不存在的地方

Laravel 5 new auth:获取当前用户以及如何实现角色?

Laravel 集合计数结果