從Laravel發出請求以存取文件的佇列任務
P粉762447363
P粉762447363 2023-09-03 13:43:56
0
1
437
<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學習者快速成長!