Laravel框架实现文件上传的方法分析

吾爱主题 阅读:122 2021-08-23 16:46:00 评论:0

本文实例讲述了Laravel框架实现文件上传的方法。分享给大家供大家参考,具体如下:

配置文件:

config/filesystems.php,

新建存储空间

?
1 2 3 4 'uplaods' => [    'driver' => 'local' ,    'root' => storage_path( 'app/uploads' ), ],

视图中:

头像:

?
1 < input type = "file" name = "headimg" />

控制器:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 $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程序设计有所帮助。

原文链接:https://www.cnblogs.com/gyfluck/p/9082826.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容