Vue2+Laravel8中Axios更新数据时File字段未更新问题
文件无法通过Axios提交到Laravel控制器的问题
提交表单后,其他数据均可正常更新,但文件字段始终无法传入请求。已在表单中添加enctype="multipart/form-data",但控制器检测不到文件存在,甚至返回了!$request->file()的响应,说明文件根本没传送到后端。以下是相关代码:
前端表单代码
<b-form @submit.prevent="update" enctype="multipart/form-data"> ... <b-form-file v-model="invoice.file" placeholder="Choose a file or drop it here..." drop-placeholder="Drop file here..." v-on:change="onChange" /> </b-form>
前端脚本代码
data() { return { invoice: { ... file: "", _method: "patch" } }; }, methods: { onChange(e) { this.file = e.target.files[0]; }, async update() { await this.axios .post(`/api/auth/outstanding-payment/${this.$route.params.id}`, this.invoice) .then((response) => { this.$router.push({ name: "apps-invoice-list" }); }) .catch((error) => { console.log(error); }); },
Laravel控制器代码
public function update(Request $request, OutstandingPayment $outstandingPayment) { $payment_voucher_supporting_doc = ''; if ($request->hasFile('file')) { $payment_voucher_supporting_doc = time() . '.' . $request->file->extension(); $request->file->storeAs('uploads/images/test', $payment_voucher_supporting_doc); if ($outstandingPayment->payment_voucher_supporting_doc) { Storage::delete('public/images/' . $outstandingPayment->payment_voucher_supporting_doc); } } else { $payment_voucher_supporting_doc = $outstandingPayment->payment_voucher_supporting_doc; } $postData = [ 'payment_voucher_file_ref_no' => $request->payment_voucher_file_ref_no, 'payment_voucher_date' => $request->payment_voucher_date, ... 'payment_voucher_received_by' => $request->payment_voucher_received_by, 'payment_voucher_supporting_doc' => $payment_voucher_supporting_doc, ]; $outstandingPayment->update($postData); }
排查补充
修改控制器添加文件检测逻辑:
if(!$request->file()) { return response()->json("Hi!"); }
提交表单后收到了"Hi!"的响应,确认文件未传入请求中。
请问问题出在哪里?
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

