从Laravel中发出请求以访问文件的队列任务
P粉762447363
P粉762447363 2023-09-03 13:43:56
0
1
484
<p>大家好,我有一个排队的 Laravel 作业,用于通过用户导入的文件向数据库中插入一些记录。但是每当我在作业中访问请求对象以获取上传的文件时,我得到的是 null。然而,在控制器中文件是正常接收的。有什么想法吗?</p> <p>在控制器中找到导入方法如下:</p> <pre class="brush:php;toolbar:false;">public function import(ImportPointRequest $request) { Storage::makeDirectory('import_logs'); $file = request()->file('file'); $fileName = 'importlog_date_' . date('Y-m-d') . '-user_' . auth()->id() . '.xlsx'; $logFile = 'import_logs/' . $fileName; $readerTypes = ['xlsx' => Excel::XLSX, 'xls' => Excel::XLS, 'csv' => Excel::CSV]; $link = route('file.show', ['import_logs', $fileName]); try { ExcelFacade::import(new PointsImportHeading(), $file); } catch (\Exception $e) { return $this->returnBadRequest(config('point.error-codes.import-fail'), $e->getMessage()); } (new PointsImport(auth()->user(), auth()->user()->account_id, $logFile))->queue( $file->getRealPath(), null, $readerTypes[request()->file('file')->getClientOriginalExtension()] )->chain([new AfterImportJob(auth()->id(), $logFile, $link)]); return $this->returnSuccess(trans('point::point.import-queued', ['module' => trans('point::point.point')])); }</pre> <p>在作业中找到 getImportedFileContent 方法如下:</p> <pre class="brush:php;toolbar:false;">protected function getUploadedFileContent(): array { return Excel::toArray(new PointsImportHeading(), request()->file('file')); }</pre> <p>问题在于这部分 <code>request()->file('file')</code> 总是返回 null。</p>
P粉762447363
P粉762447363

全部回复(1)
P粉852114752

您的方法是不正确的。在Laravel中,请求的生命周期从请求到达服务器开始,当响应发送回用户的浏览器时结束。当您在Laravel中排队一个作业时,这意味着该作业将在稍后处理,甚至可能在不同的服务器上处理。当作业实际运行时,原始的请求生命周期已经结束。因此,您无法在排队的作业中访问请求数据。

如果您需要在排队的作业中使用上传的文件,您需要将上传的文件存储在作业可以访问的位置。这可以是您服务器的文件系统或云存储服务。

在您的控制器中,您已经临时存储文件以便使用Excel进行处理:

$file = request()->file('file');

然而,您没有持久化文件,这就是为什么在作业运行时文件不可用的原因。您需要将文件存储在更持久的地方。

在永久存储文件后,您可以从新位置读取文件。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!