laravel5.5框架的上传图片功能实例分析【仅传到服务器端】
程序员文章站
2023-12-01 22:57:46
本文实例讲述了laravel5.5框架的上传图片功能。分享给大家供大家参考,具体如下:
这里面包含单张和多张图片的上传
首先先来前端页面的html
本文实例讲述了laravel5.5框架的上传图片功能。分享给大家供大家参考,具体如下:
这里面包含单张和多张图片的上传
首先先来前端页面的html
<!doctype html> <html> <head> <title>上传图片</title> </head> <body> <form method="post" action="{{url('uploadimgs')}}" enctype="multipart/form-data"> {{csrf_field()}} <input type="file" name="filename[]"><br/> <input type="file" name="filename[]"><br/> <input type="file" name="filename[]"> <button type="submit">上传图片</button> </form> </body>
记得路径那改成post
然后就是后台代码
到config/filesystem.php下增加一个
'upload' => [ 'driver' => 'local', 'root' => 'uploadimages' ],
use illuminate\http\request;
// 单张图片 public function uploadimg(request $request){ if ($request->hasfile('filename')) { $postpics = $request->file('filename'); foreach ($postpics as $k => $v) { $extension = $v->extension(); $rule = ['jpg', 'png', 'gif', 'jpeg']; if (!in_array($extension, $rule)) { return '图片格式需要为jpg,png,gif格式'; } $dir = date('ymd'); $filename = time() . mt_rand(1, 999) . ".jpg"; $storeresult = $v->storeas('filename', $dir . "/" . $filename, 'upload');// 默认保存位置是要到filesystem.php设置,保存到storage/app/.. $output[] = [ 'img_url' => "images/" . $storeresult, 'uid' => $uid, 'exam_id' => $examid, 'question_id' => $questionid, ]; } db::table('x2_upload_img')->insert($output); echo "写到数据库了,图片上去了只是ide加载很慢"; } else { exit('未获得到上传文件,或上传失败'); }
// 多图上传 public function uploadimgs(request $request){ if($request->hasfile('filename')){ $postpics = $request->file('filename'); foreach ($postpics as $k=>$v){ $extension = $v->extension(); $rule = ['jpg','png','gif','jpeg']; if(!in_array($extension,$rule)){ return '图片格式需要为jpg,png,gif格式'; } $storeresult = $v->storeas('filename','201810/test1.jpg','upload');// 默认保存位置是要到filesystem.php设置,保存到storage/app/.. $output[] = [ 'extension' => $extension, 'store_result' => $storeresult ]; } echo "<pre>"; print_r($output);die; } exit('未获得到上传文件,或上传失败'); }
// 上传图片第二种方式(form表单直接传过来) public uploadimg(){ $image = $_files["photo"]["tmp_name"]; $fp = fopen($image, "r"); $file = fread($fp, $_files["photo"]["size"]); //二进制数据流 //保存地址 $imgdir = './uploads/'; //要生成的图片名字 $filename = date("ym")."/".md5(time().mt_rand(10, 99)).".png"; //新图片名称 $newfilepath = $imgdir.$filename; $data = $file; $newfile = fopen($newfilepath, "w"); //打开文件准备写入 fwrite($newfile, $data); //写入二进制流到文件 fclose($newfile); //关闭文件 }