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

1、效果图(每点击一次‘添加选项’,就会有一个新的 file 框来添加新的图片)

2、view

<!--不要忘了引入jquery文件-->
<!-- post传值方式和文件传输协议一定要加上 -->
<input type="file" name="image[]">
<input type="button" id="add" name="add" value="+ 添加选项">
<button type="submit" name="submit">添加</button>
 
<script type="text/javascript">
  $("#add").click(function(){
    $(this).before('<input type="file" name="image[]">');
  });
</script>

3、controller

//接收从view来的图片数组
$image=request()->file('image');
 
//实例化模型,并调用里面的添加图片的方法
$details = new details();
$info = $details->add($image);
if($info === 1)
{
  return '操作成功';
}
else
{
  return '操作失败';
}

4、model

//将接收到的 $image foreach遍历添加
foreach($image as $image)
{
  //实例化模型
  $details = new details();
  $time=date('ymd',time());
  //将当前的时间戳定义为文件名
  $filename=time();
  //检测是否存在存放图片的文件夹
  if(!file_exists(root_path . 'public' . ds .'static'. ds .'img'))
  {
    //创建文件
    mkdir(root_path . 'public' . ds .'static'. ds .'img');
  }
  //上传图片
  $info=$image->move(root_path . 'public' . ds .'static'. ds .'img'.ds.$time,$filename);
  //将图片路径存放在数据库中
  $details->url = $time.ds.$info->getfilename();
  $details->allowfield(true)->save();
}
return 1;

5、over over over