laravel框架中上传图片,并在本地显示

发布时间 2023-04-27 09:41:33作者: 还好阿卡
 1 //处理文件上传
 2         if ($request->hasFile('image')&&$request->file('image')->isValid()){
 3             //对上传文件做必要处理
 4             $filename=date('ymdHis').rand(100000,999999).'.'.$request->file('image')->extension();
 5             //移动文件到指定目录下
 6             $request->file('image')->move('./statics/upload',$filename);
 7         }
 8         //验证成功后提示消息
 9 //        echo "成功";
10         $data=$request->only('name','sum','price');
11         $data['image']='/statics/upload/'.$filename;
12         $res=Shop::create($data);
13         if ($res){
14             return "<script>alert('添加成功')</script>";
15         }else{
16             return "失败";
17         }

上面是控制器代码,(记得在public目录下面创建一个   static/upload  目录)    下面是在前端展示的代码

 1  @foreach($data as $v)
 2                 <tr class="text-c">
 3                     <th><input type="checkbox" name="" value=""></th>
 4                     <th>{{$v->id}}</th>
 5                     <th>{{$v->name}}</th>
 6                     <th>{{$v->sum}}</th>
 7                     <th>{{$v->price}}</th>
 8                     <th>
 9                         <img src="{{$v->image}}" width="150px">
10                     </th>
11                     <th>{{$v->created_at}}</th>
12                     <th>
13                         <a href="">操作</a>
14                     </th>
15                 </tr>
16             @endforeach

下面是效果图