使用Layui上传图片,并进行压缩(非原创,证实可用)

这边是html

<div class="popBox pop_m"><span class="closePopBt">关闭</span>
    <div class="hr20"></div>
    <form class="layui-form" action="">
        <a href="javascript:void(0)" class="aLine margin_r15 uploadpic_btn">图片</a>            
        
            <div class="upload_piclist"> </div>
        </div>
        <div class="popBottomBt"> <a href="javascript:void(0)" class="button send_smit">发送</a> </div>
    </form>
</div>

  

贴上我自己的代码

<script>
function canvasDataURL(file, callback) { //压缩转化为base64
    var reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function (e) {
      const img = new Image()
      const quality = 0.5 // 图像质量
      const canvas = document.createElement('canvas')
      const drawer = canvas.getContext('2d')
      img.src = this.result
      img.onload = function () {
        canvas.width = img.width
        canvas.height = img.height
        drawer.drawImage(img, 0, 0, canvas.width, canvas.height)
        convertBase64UrlToBlob(canvas.toDataURL(file.type, quality), callback);
      }
    }
  }
 
  function convertBase64UrlToBlob(urlData, callback) { //将base64转化为文件格式
    const arr = urlData.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    callback(new Blob([u8arr], {
      type: mime
    }));
 }
    
    
layui.use(['layer','upload'],function() {
    var form = layui.form
	,upload = layui.upload;
	
	$(".closePopBt").on("click", function(){
		var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
		parent.layer.close(index); //再执行关闭        
	});	
	
  //多图片上传
	var upload = layui.upload;
	upload.render({
		elem: '.uploadpic_btn',
		url: '/workflow/comment/upload',
 		accept: 'images', //只允许传图片
//		size: 10240, //限制文件大小,单位 KB
		multiple: true,
                auto:false,
                choose:function(obj){
                    var files = obj.pushFile();
                    var filesArry = [];
                    for (var key in files) { //将上传的文件转为数组形式
                      filesArry.push(files[key])
                    }
                    var index = filesArry.length - 1;
                    var file = filesArry[index]; //获取最后选择的图片,即处理多选情况

                    if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
                        .replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
                      return obj.upload(index, file)
                    }
                    canvasDataURL(file, function (blob) {
                      var aafile = new File([blob], file.name, {
                        type: file.type
                      })
                      var isLt1M;
                      if (file.size < aafile.size) {
                        isLt1M = file.size
                      } else {
                        isLt1M = aafile.size
                      }

                      if (isLt1M / 1024 / 1024 > 2) {
                        return layer.alert('图片压缩之后还是大于2M,请压缩之后上传!');
                      } else {
                        if (file.size < aafile.size) {
                          return obj.upload(index, file)
                        }
                        obj.upload(index, aafile)
                      }
                    })
                },
		before: function(obj) {
                    //预读本地文件示例,不支持ie8
//                    obj.preview(function(index, file, result) {
//                        
//                    });
		},
		done: function(res) {
                    //上传完毕
                    $('.upload_piclist').append('<div class="uploadpic"><div class="pic"><img src="' + res.info.path_url + '" alt="' + res.info.title + '" class="layui-upload-img"></div><span attr_old_name='+res.info.title+' attr_new_name='+res.info.new_name+'  path='+res.info.path+' class="delpic_bt"></span></div>')
		}
	});

  

posted on 2019-10-23 15:10  朽木大叔  阅读(3930)  评论(0编辑  收藏  举报

导航