本文實例講述了Laravel框架實現(xiàn)文件上傳的方法。分享給大家供大家參考,具體如下:
配置文件:
config/filesystems.php,
新建存儲空間
'uplaods' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
],
視圖中:
頭像:
input type="file" name="headimg" />
控制器:
$file = $request->file('headimg');
if($file $file->isValid()){
// //獲取原圖片信息
$ext = $file->getClientOriginalExtension();
$originalName = $file->getClientOriginalName();
$type = $file->getClientMimeType();
$path = $file->getRealPath();
//驗證圖片類型,大小等
//保存圖片
$save_name = date('YmdHis',time()) .'-' .uniqid() .'.'. $ext;
$bool = Storage::disk('uploads')->put($save_name,file_get_contents($path));
if(!$bool){
return redirect()->back()->withErrors('圖片上傳失敗')->withInput();
}
}else{
return redirect()->back()->withErrors('請上傳圖片')->withInput();
}
//如果驗證通過,則繼續(xù)執(zhí)行下面的代碼
$data = $request->input('Student');
//圖片全路徑
$img_web_path = storage_path('app/uploads') . '/' .$save_name;
//圖片相對路徑
$data['headimg'] = $save_name;
if(Student::create($data)){
return redirect('Student/index')->with('success','添加成功');
}else{
return redirect()->back();
}
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。
您可能感興趣的文章:- Laravel中使用阿里云OSS Composer包分享
- Laravel框架文件上傳功能實現(xiàn)方法示例
- 利用laravel+ajax實現(xiàn)文件上傳功能方法示例
- laravel 實現(xiàn)阿里云oss文件上傳功能的示例