laravel5.5框架的上传图片功能实例分析【仅传到服

本文实例讲述了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('未获得到上传文件,或上传失败');
}


      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1875.html