我有一個這樣的表格:
<form action="{{ route('popups.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div id="dynamic_field">
<label>Date of showing</label>
<input type="text" id="date" name="datep" class="form-control datepicker" value="" autofocus>
<label for="title" class="control-label">Title</label>
<input type="text" id="title" name="title" class="form-control" value="" autofocus>
<label for="link" class="control-label">Link</label>
<input type="text" id="link" name="linkp[]" class="form-control" value="" autofocus>
<label for="bio" class="control-label">Text</label>
<textarea class="form-control" name="bio[]" rows="3"></textarea>
<label for="filep" class="control-label">Image</label>
<input type="file" class="form-control-file" id="filep" name="filep[]">
<button class="btn btn-success" type="submit">Submit</button>
<a id="add" class="btn btn-info" style="color:white">Add new form</a>
</div>
</form>
如您所見,我添加了一個鏈接,id="add"用于使用 javascript 動態添加其他表單欄位。
所以這意味著用戶可以添加多個影像、文本和鏈接。這就是為什么我使用filep[],bio[]和linkp[], 作為這些表單欄位的名稱(為了將它們保存為陣列)。
然后在控制器,我添加了這個:
public function store(Request $request)
{
try{
$data = $request->validate([
'datep' => 'nullable',
'title' => 'nullable',
'linkp' => 'nullable',
'bio' => 'nullable',
'filep' => 'nullable',
]);
$newPop = Popup::create([
'datep' => $data['datep'],
'title' => $data['title']
]);
$files = $request->file('filep');
if($request->hasFile('filep'))
{
foreach ($files as $file) {
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
$request->filep->move(public_path('popups'), $newImageName);
Popup::where('id',$newPop->id)->update(['image_path'=>",".$newImageName]);
}
}
}catch (\Exception $e) {
dd($e);
}
return redirect()->back();
}
因此,對于每個影像,我嘗試將其移動到public/popups檔案夾中,然后它應該使用 id 更新表的現有記錄$newPop->id。
但它向我展示了這個錯誤:
呼叫陣列上的成員函式 extension()
這是指這一行:
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
那么這里出了什么問題呢?如何使用陣列上傳多個影像?
uj5u.com熱心網友回復:
你可以試試這個——
if($files=$request->file('filep')){
foreach ($files as $key=>$file) {
$extension = $file->getClientOriginalName();
$fileName = time().'-' .$request->name.'.'.$extension; // I don't know where did you get this $request->name, I didn't find it on your code.
$created = Popup::create([
'datep' => $request->datep[$key],
'title' => $request->title[$key],
'image_path' => $fileName
]);
if($created){
// $file->move('popups',$fileName); to store in public folder
// If you want to keep files in storage folder, you can use following : -
Storage::disk('public')->put('popups/'.$location,File::get($file));
// Dont't forget to run 'php artisan storage:link'
// It will store into your storage folder and you can access it by Storage::url('file_path)
}else{
// Your error message.
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351643.html
標籤:php 拉拉维尔 上传文件 laravel-5.8
上一篇:根據非空值顯示圖示
下一篇:如何在laravel中更新陣列
