Laravel文件上传配置与实现
本示例详细解析了如何在Laravel框架下完成文件上传功能,供开发者参考借鉴。
首先需要进行基础配置:
编辑配置文件 config/filesystems.php,
以建立新的存储空间。
'uplaods' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
],
在前端视图中:
需包含头像上传的表单元素。
后端控制器负责接收请求并处理文件。
$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();
}
//如果验证通过,则继续执行下面的代码
$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();
}
期望上述内容能对使用Laravel进行PHP开发的读者提供有益帮助。