TP5 example of the method of uploading multiple pictures (with attachment selection) using layui

Time:2021-12-30

TP5 uses layui to upload multiple pictures (with attachment selection). How to load layui is not described in detail here. You can baidu if necessary

HTML code is mainly processed in JQ. All the completion methods are original. It may not be the simplest, but it can also achieve results

{include file="public/header" /}
<body>
<div>
      <span>
        < a href = "" > Home Page</a>
        < a href = "" > multi select picture list</a>
        <a>
          < cite > add multiple pictures < / cite ></a>
      </span>
  <a style="line-height:1.6em;margin-top:3px;float:right" href="javascript:location.replace(location.href);"  Rel = "external nofollow" title = "Refresh" >
    <i style="line-height:30px">ဂ</i></a>
</div>
<div>
  < div style = "font size: 14px" > add multiple pictures < / div >
  <div style="width:100%;height: 5px;background-color: #077ee3;margin-top: 5px;margin-bottom: 20px"></div>
 
    <form  action="" enctype="multipart/form-data" method="post" role="form" onSubmit="return check()">
 
 
      <div>
        < button type = "button" > multi picture upload < / button >
        < a onclick = "selectimg ('select picture ',' {: URL ('selectimg ')}', '1000', '600')" href = "javascript:;" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
        <i></ i> Select Picture
        </a>
        <blockquote style="margin-top: 10px;">
          Preview:
          <div></div>
        </blockquote>
      </div>
 
      <input  name="url" type="hidden">
      <!--<button type="button"  onclick="test()">-->
        <!-- Test -- >
      <!--</button>-->
    <div>
      <label for="">
      </label>
      <button type="submit" lay-filter="add" lay-submit="">
        increase
      </button>
 
    </div>
  </form>
</div>
<style>
  .imgInput{
    width: 600px;
    height: 35px;
  }
  .layui-form-label{
    font-size: 14px;
    width: 100px;
  }
 
  select{
    width: 500px;
  }
  #pre_img{
    display: none;
    padding: 5px;
    border: 1px solid #999;
  }
  #demo2{
    display: flex;
    display: -webkit-flex;
    /*justify-content: space-between;*/
    flex-direction: row;
    flex-wrap: wrap;
  }
  .img{
    width: 150px;
    height: 150px;
  }
  .btnAdd{
    margin-top: 40px;
  }
  .img_item{
    display: flex;
    flex-direction: column;
    text-align: center;
    margin-right: 20px;
    margin-bottom: 20px;
  }
  .delimg{
    text-align: center;
    line-height: 20px;
    width: 160px;
    height: 20px;
    background-color: red;
    color: white;
    margin-top: 5px;
  }
</style>
 
<script>
  function check(){
    $('input[name="url"]').val(urlList);
    var str = $('input[name="url"]').val();
 
    if(str ==''|| str==null || str=='undefined'){
      Alert ("please select a picture");
      return false;
    }
 
  }
 
  function selectImgGo($url,$urlWeb){
    var index = 0;
    if(urlList.length>0){
      index = urlList.length;
    }
      var img = $([
        '<div>',
        '<div style="overflow:hidden;">',
        '<img src="'+ $urlWeb +'" alt="' + $url +'" style="max-width:150px;"></div>',
        '<div onclick=delImg("'+ index +'")  href="javascript:;"  Rel = "external nofollow" rel = "external nofollow" rel = "external nofollow" rel = "external nofollow" style = "cursor: pointer" > delete < / div > < / div > '
      ].join(''));
      $('#demo2').append(img);
 
    urlList.push($url);
    imgList.push($urlWeb);
  }
  var imgList = [];
  var urlList = [];
  layui.use(['upload','jquery'],function () {
    $ = layui.jquery;
    var upload = layui.upload;
    //Multi picture upload
    upload.render({
      elem: '#upload_img'
      , URL: "{: URL ('share / upload_img ')}" // upload interface
      ,multiple: true
      ,before: function(obj){
        //Read ahead local file example, IE8 is not supported
        obj.preview(function(index, file, result){
 
        })
      }
      ,done: function(res){
        var index0 = 0;
        if(urlList.length>0){
          index0 = urlList.length;
        }
        var img0 = $([
          '<div>',
          '<div style="overflow:hidden;">',
          '<img src="'+ res.msg +'"  style="max-width:150px;"></div>',
          '<div onclick=delImg("'+ index0 +'")  href="javascript:;"  Rel = "external nofollow" rel = "external nofollow" rel = "external nofollow" rel = "external nofollow" style = "cursor: pointer" > delete < / div > < / div > '
        ].join(''));
        $('#demo2').append(img0);
        urlList.push(res.url);
        imgList.push(res.msg);
      }
      ,error: function(){
//        layer. close(layer.msg());// Close the upload prompt window
        //Request exception callback
      }
 
    });
  });
 
  function delImg(index){
    urlList.splice(index,1);
    imgList.splice(index,1);
    $('#demo2').empty();
    for (var i=0;i<imgList.length;i++){
      var img0 = $([
        '<div>',
        '<div style="overflow:hidden;">',
        '<img src="'+ imgList[i] +'"  style="max-width:150px;"></div>',
        '<div onclick=delImg("'+ i +'")  href="javascript:;"  Rel = "external nofollow" rel = "external nofollow" rel = "external nofollow" rel = "external nofollow" style = "cursor: pointer" > delete < / div > < / div > '
      ].join(''));
      $('#demo2').append(img0);
    }
  }
 
  /*Select Picture*/
  function selectImg(title,url,w,h){
    x_admin_show(title,url,w,h);
  } 
</script>
</body> 
</html>

PHP code

//PHP layui image upload
    public function upload_img(){
        $file = request()->file('file'); //  Get uploaded files
        if($file==null){
            Exit (json_encode (array ('code '= > 1,' MSG '= >' picture not uploaded ');
        }else{
            //5. Make conditional restrictions on uploaded files (type, size, etc.)
            $map = [
                'ext' = > 'JPG, PNG, GIF, JPEG', // dropout
                'size '= > 320000000, // max 3M
            ];
            //6. Compare the uploaded files. If they are qualified, transfer them to the preset public / uploads directory
            //Returns the saved file information info, including file name, size and other data
            $info = $file->validate($map)->move(ROOT_PATH . 'public/uploads/img');
            //Get picture width and height
            list( $width , $height , $type , $attr ) = getimagesize ($info->getPathName());
 
            if(is_null($info)){
                $this->error($info->getError());
            }
            $img = str_replace('\\','/',$info->getSaveName());
            //Save attachment
            $annexData['filesize'] = $info->getInfo()['size'];
            $annexData['mimetype'] = $info->getInfo()['type'];
            $annexData['filename'] = $info->getInfo()['name'];
            $annexData['imagewidth'] = $width;
            $annexData['imageheight'] = $height;
            $annexData['type'] = 'img';
            $annexData['url'] = $img;
            AAnnexModel::create($annexData);
            $img = constant("URL")."/uploads/img/".$img;
            exit(json_encode(array('code'=>0,'msg'=>$img,'url'=>$annexData['url'])));
        }
 
    }
 
 //Add page to multiple pictures
    public function addImages(){
        if($this->request->isPost()){
            //2. Obtain the submitted data. Finally, the true parameter indicates that it is obtained together with the uploaded file
            $data = $this->request->param(true);
            $res = AImagesModel::create($data);
            if(is_null($res)){
                $this - > error ('failed to add file ');
            }else{
                $this - > success ('File added successfully... ', URL ('imageslist');
            }
            return;
        }
        return $this->fetch('images_add');
    }

This is the end of this article about the method of TP5 using layui to upload multiple images (with attachment selection). For more information about TP5 multi image upload, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!