Laravel10+Filament3中生成docx文件后如何触发浏览器下载?
解决方案
在Filament 3的Header Action中触发文件下载,核心是利用Filament允许动作的action方法直接返回Laravel的响应实例,浏览器会自动处理该响应触发下载流程。以下是具体实现步骤:
1. 优化文件下载方法
修改GenerateEmployeeCard类的download方法,确保返回正确的文件响应,并添加下载后自动清理文件的逻辑:
public function download(): \Symfony\Component\HttpFoundation\BinaryFileResponse { $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($this->phpWord, $this->outputFileFormat); $filename = $this->getDestFilename(); // 复用你已定义的文件名逻辑 $filePath = storage_path($filename); $objWriter->save($filePath); // 返回下载响应,同时设置下载后自动删除文件 return response()->download($filePath, $filename) ->deleteFileAfterSend(true); }
2. 修改Filament动作逻辑
在EditEmployee.php的getHeaderActions方法中,调整GenerateWordCard动作的闭包,直接返回下载响应:
protected function getHeaderActions(): array { return [ Actions\DeleteAction::make(), Action::make('GenerateWordCard') ->label('Generate card in word-file') ->action(function (): \Symfony\Component\HttpFoundation\Response { $employeeCard = new GenerateEmployeeCard; $employeeCard->setEmployee(employee: $this->record, showHireInfo: true); $employeeCard->generate(); $destFilename = $employeeCard->getDestFilename(); // 发送成功通知 Notification::make() ->title("Employee card was successfully generated and downloaded as \"{$destFilename}\" file!") ->success() ->send(); // 返回下载响应,Filament会自动将其发送给浏览器 return $employeeCard->download(); }), ]; }
关键说明
- Filament的动作闭包支持返回
Symfony\Component\HttpFoundation\Response实例,框架会直接将该响应传递给浏览器,从而触发文件下载。 - 使用
deleteFileAfterSend(true)可以避免storage目录中堆积大量生成的临时文件,节省服务器空间。 - 通知会在下载触发前发送,用户会看到成功提示的同时,浏览器开始下载文件。
内容的提问来源于stack exchange,提问作者Petro Gromovo
相关产品推荐
相关产品推荐

