【发布时间】:2020-09-13 05:59:33
【问题描述】:
我在我的数据库中保存文件时遇到问题我已经完成了编码,但不知何故编码没有读取我的 File 函数的第一行代码,因为它一直读取将保存 noimage.jpgif 的 else 行,没有检测到文件在提交期间。我认为问题出在我的刀片上。但我想不通。
选择文件后,文件名也没有出现。
数据也保存到我的数据库中,但名称为 noimage.jpg,即使我尝试提交图像。
public function store(Request $request)
{
$this->validate($request,[
'location' =>'required',
'event_image'=>'image|nullable|max:1999',
'availability'=>'required',
]);
//handle the file upload
if($request ->hasFile('event_image')){ // to check if user has opted to upload the file
// get filename with extention
$filenameWithExt = $request->file('event_image')->getClientOriginalName();
//get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//get ext (extention)
$extension =$request->file('event_image')->getClientOriginalExtension();
//filename to store
$fileNameToStore = $filename .'_'.time().'.'.$extension;
//upload image
$path = $request->file('event_image')->storeAs('public/event_images',$fileNameToStore);
}else{
$fileNameToStore ='noimage.jpg'; // if user dont have any file this name will be put on the database
}
$event = new Event;
$event->location = $request->input('event_location');
$event->event_image =$fileNameToStore;
$event->availability =$request->input('event_availability');
$event->admin_id = auth()->user()->id;
$event->save();
}
<form class="form-horizontal" action="{{route('event.store')}}" method="POST" enctype="multipart/form-data">
@csrf
<div class="form-group row">
<label for="event_image" class="col-sm-2 col-form-label">Event Picture</label>
<div class="col-sm-10">
<div class="custom-file">
<input type="file" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile" name="event_image" id="event_image"></label>
</div>
</div>
</div>
</div>
</form>
【问题讨论】:
-
欢迎您,在您的代码中
if($request ->hasFile('event_image')){这一行的代码中,$request 和对象运算符(箭头)之间有空格,这是在stackoverflow 上编写还是在您执行的代码中出现的错误还有 -
我不会将 noimage.jpg 存储在您的数据库中。最好在您的数据库中保留一个 NULL 值,并在您的视图中检查要显示的图像。