JQ input框单多图上传

5 篇文章 0 订阅

上传文件大家前端都是用input file上传图片,今天使用layer插件的配合写一个支持单多图上传的前端
后台还是如此一会也有upload方法
1.引入layer.js文件是必须的 (同时也要引入jquery-1.8.3.min.js)
HTML

//1.srcChanged 这个方法 还有 for 命名保证统一 
//2.多图上传 多一个参数multiple="multiple"
//3.id="preview_lic_img" 和第一条对应命名 id层是为了图片展示位置 追加到对应层内
//单图上传
//提示框
<div class="error_tip" id="error" style="display: none;"></div>
//以下正文
<div class="content">
    <div class="flexL mt-10" style="flex-wrap: wrap;">
        <label for="lic_img" class="uploadimg flexR lic_img" >
            <input id="lic_img" onchange="srcChanged('license_img','lic_img')" type="file" name="" />							
        </label> 
        <div id="preview_lic_img">
            <div class="upimgs mr-15 mb-10">
                <img src=""  />
                <em class="flexR" onclick="removeImg(this,'license_img','lic_img','1')"></em>
            </div>
        </div>                                    
    </div>
</div>
<input id="license_img" type="hidden" name="license_img" value="" />
//多图上传
<div class="content">
     <div class="flexL mt-10" style="flex-wrap: wrap;" id="preview_aut_img">
         <div class="upimgs mr-15 mb-10">
              <div class="Img flexR">
                  <img src="" />
              </div>          
              <em class="flexR" onclick="removeImg(this,'author_img','aut_img','5')"></em>
          </div>
      </div>                                
      <label for="aut_img" class="uploadimg  flexR aut_img">
          <input id="aut_img" onchange="srcChanged('author_img','aut_img')" type="file" name="" data-maxnum="5" multiple="multiple" />
      </label>
  </div>                            
  <input id="author_img" type="hidden" name="author_img" value="" />

JQ

function srcChanged(fileId,previewId){
      var files = $('#' + previewId)[0].files;
      var maxNum = $('#' + previewId).data('maxnum');  //最多上传5张图片
      if(maxNum > 1){
          var picnum = $('#preview_' + previewId).children('.upimgs').length;
          if(picnum >= maxNum){
              $("#error").show().delay(2000).hide(200);
              $("#error").text("最多只能上传"+maxNum+"图片");
              return false;
          }
      }
      var fileCount = files.length;
      if(maxNum > 1 && (picnum+fileCount) >=maxNum){
          fileCount = maxNum - picnum;
      }
      var formData = new FormData();
      for (var i = 0; i < fileCount; i++) {
          var img_size = files[i].size;
          if((img_size / 1024) > 2048){
              $("#error").show().delay(2000).hide(200);
              $("#error").text("图片大小不能超过2M");
        	   return false;
      		}
          formData.append("fileupload[]", files[i]);   // 文件对象 ,fileupload必须加中括号   
      }
      formData.append("thumb",'1');
      formData.append("thumb_width",'60');
      formData.append("thumb_height",'60');
      formData.append("pictype",'jxs_author');
      layer.load(2);
      $.ajax({
          url: '/php/upload/',
          type: 'POST',
          cache: false,
          data: formData,
          processData: false,
          contentType: false,
          dataType:'json'
      }).done(function(res) {
          layer.closeAll('loading');
          if(res.resultId == 0){
              var picurl = res.Data;
              if ($("#" + previewId).prop('multiple')) {
                  var html = '';
                  var valObj = [];
                  if ($("#" + fileId).val() !== '') {
                      valObj = $("#" + fileId).val().split(",");
                  }
                  $.each(picurl, function (key, val) {         
                      picnum++;
                      html += '<div class="upimgs mr-15 mb-10" ><div class="Img flexR">\n\
                              <img src="' + val + '" />\n\
                              <em class="flexR" onclick=\'removeImg(this,"'+fileId+'","'+previewId+'",5)\'>✕</em></div></div>';
                      valObj.push(val);
                  });
                  $('#preview_' + previewId).append(html);
                  $("#" + fileId).val(valObj.join());
                  var num = maxNum - picnum;
                  if(num == '0'){
                      $('.'+previewId).hide();
                  }
                  $('#'+previewId).val('');
              } else {
                  $('#preview_' + previewId).html('<div class="upimgs mr-15 mb-10"><img src="' +  picurl[0] + '"><em class="flexR" οnclick=\'removeImg(this,"'+fileId+'","'+previewId+'",1)\'>✕</em></div>');
                  
                  $("#" + fileId).val(picurl[0]);
                  $('.'+previewId).hide();
              }
          }else{                
              $("#error").show().delay(2000).hide(200);
              $("#error").text(res.Data);
              return false;
          }

      }).fail(function(res) {
          layer.closeAll('loading');
          $("#error").show().delay(2000).hide(200);
          $("#error").text("图片太大");                
          return false;
      });
  }
  //删除图片
  function removeImg(r,fileId,previewId,num) {
      var picsrc = $(r).prev('img').attr('src');
      //添加用户真删除图片
      if(num > 1){//删除多张图片
          var ptObj = $("#"+fileId).val().split(',');
          var idx = $.inArray(picsrc,ptObj);
          if(idx != -1){
              $.post("/presence/delImgUrl/",{img_url:picsrc},function(data){
                  var data = JSON.parse(data);
                  if(data.resultId == 0){
                      ptObj.splice(idx,1);
                      $("#"+fileId).val(ptObj.join());
                      $('#'+previewId).val('');
                      if(fileId =='author_img'){
                          $(r).parent().parent().remove();
                      }else{
                          $(r).parent().remove();
                      }                        
                      $('.'+previewId).show();
                  }else{
                      $("#error").show().delay(2000).hide(200);
                      $("#error").text("删除图片失败");
                  }
              })
          }else{
              layer.alert('删除图片失败');
          }
      }else if(num == 1){//删除单张图片
          $.post("/presence/delImgUrl/",{img_url:picsrc},function(data){
              var data = JSON.parse(data);
              if(data.resultId == 0){
                  $('#preview_' + previewId).html('');
                  $('.'+previewId).show();
                  $("#"+fileId).val('');
                  $('#'+previewId).val('');
              }else{
                  $("#error").show().delay(2000).hide(200);
                  $("#error").text("删除图片失败");
              }
          })
      }	
  }

PHP

private $upconfig = [
    'allowSuffix'=> ["jpg","jpeg", "png", "pjpeg","gif","bmp","x-png","csv",'xlsx','xls','pdf'],
    'rootPath'=> "./static/uploads/",
    'savePath'=> "content/",
    'maxSize'=> 2097152, //2M 2 * 1024 * 1024;
];
public function uploadAction(){
    if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
        $photoimg = $_FILES['photoimg'];
        $import_data = $_FILES['import_data'];

        $className = "preview";
        if(isset($_POST['pictype']) && !empty($_POST['pictype'])){
            $this->upconfig['savePath'] = 'content/'.$_POST['pictype'].'/';
        }
        $url_path = parse_url($_SERVER['HTTP_REFERER'])['path'];
        $action_path = explode('/',$url_path);
        $action = strtolower($action_path[1].'/'.$action_path[2]);
        $this->upconfig['maxSize']=$this->upconfig['maxSize']*2.5;
        if (array_key_exists('import_data',$_FILES)) { //上传文件
            $this->upconfig['savePath'] = 'improt_data/';
            $this->upconfig['saveName'] = '';  //是否重命名文件
            $this->upconfig['prefix'] = ''; //重置前缀
            $this->upconfig['autoSub'] = false;
            $this->upconfig['allowSuffix'] = ["csv",'xlsx','xls'];
        }

        $up_ins = Comm_Uploadimg::getInstance($this->upconfig);
        $res = $up_ins->uploadFile();
        if($res){
            $img_ins = Comm_Image::getInstance();
            foreach($res as $key=>$file){
                $imgpath =  $this->upconfig['rootPath'] . $file['savepath'] . $file['savename'];
                if(in_array($file['ext'],$img_ins->compress_type)){ //图片文件压缩处理
                    $img_ins->open($imgpath)->compress()->save($imgpath);//压缩处理;
                }
                $info[] = substr($imgpath, 1);
            }
            $response =  Comm_Tools::returnMsg(0,$info,1);
        }else{
            $response =  Comm_Tools::returnMsg(1,$up_ins->getError(),1);
        }
        exit($response);
    }
}

php部分的代码没有啥问题,就是一个上传代码,需要返回的是图片路径,jq根据路径去处理,
前后端限制图片大小2M

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值