Layui 图片上传压缩 单选及多选

layui图片上传压缩 单选以及多选

提示:obj.upload(index, aafile)针对单个文件上传


一、页面显示

<div class="layuimini-container">
        <div class="layuimini-main" id="autoHtml">
            <div class="layui-form layuimini-form" lay-filter="submitForm">
                <div class="layui-row">
                    <div class="layui-col-md12">
                        <button type="button" class="layui-btn" id="upload">上传图片</button>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            预览图:
                            <div class="layui-upload-list image-box" id="preview"></div>
                        </blockquote>
                    </div>
                </div>
                <div id="submitButton" class="layui-row">
                    <div class="layui-col-md12">
                        <div class="layui-input-block"><button class="layui-btn layui-btn-normal " id="save" lay-submit lay-filter="saveBtn">确认保存</button></div>
                    </div>
                </div>
            </div>

        </div>
    </div>

二、图片压缩

压缩转化为base64

	/**
	*压缩转化为base64
	*/
   function canvasDataURL(file, callback) { 
      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);        
             
             }
         }
   }

将base64转化为文件格式

function convertBase64UrlToBlob(urlData, callback) { 
                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
                }));
            }

三、upload单选

说明:单选上传时,由于layui框架里的upload特性,每次选择图片时,obj.pushFile()方法获取图片是一直叠加,如果需要对图片进行加工重新上传时,每次都需要删除前一次上传图片的内容

upload.render({
    elem: '#upload',
    url: url //存放自己需要上传图片的路径
    headers: {
         token: token
     },
     method: 'POST',
     auto: false,
     choose: function(obj) {
       //预读本地文件示例,不支持ie8
       obj.preview(function(index, file, result) {
           var html = '<div class="img-content" id="content-' + index + '">';
           html += '<input type="hidden" name="paths[]" id="path-' + index + '">'
           html += '<img src="' + result + '" alt="' + file.name + '" class="img-100" id="img-' + index + '">';
           html += '<div style="width: 95px; margin:1px auto 0px; "><div class="layui-progress " lay-showpercent="yes" lay-filter="progress-' + index + '"> <div class="layui-progress-bar" lay-percent=""></div></div></div>';
           html += '<div class="img-cancel" id="cancel-' + index + '">x</div>';
           html += '</div>';
           $('#preview').html(html);
           //点击图片放大
           $('body').on('click', '#img-' + index, function(e) {
               layer.open({
                   type: 1,
                   title: false,
                   closeBtn: 1,
                   shadeClose: true,
                   area: ['500px', 'auto'],
                   content: "<img src=" + result + " />"
               });
           });
       });
       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 (file.size > 200 * 1024) {
           canvasDataURL(file, function(blob) {
             var aafile = new File([blob], file.name, {
                  type: file.type
              })
             obj.upload(index, aafile)
            })
        } else {
            obj.upload(index, file)
       }
    },
    done: function(res, index, upload) {
        if (res.code == 200) {
            $("#path-" + index).attr("value", res.data.avatar)
            //删除按钮
            $('body').on('click', '#cancel-' + index, function() {
                $("#content-" + index).remove();
            });

        } else {
            $("#content-" + index).remove();
        }

    },
   progress: function(n, elem, res, index) {

       if (n == 100) {
           layer.msg('上传完毕', {
               icon: 1
           });
       }
       element.progress('progress-' + index, '100%'); //进度条复位
   },
   error: function(index, upload) {
       $("#content-" + index).remove();
   }
 })

四、 upload多选

代码如下(示例):

var selectArr=[];
upload.render({
    elem: '#upload',
    url: url //存放自己需要上传图片的路径
    headers: {
         token: token
     },
     method: 'POST',
     auto: false,
     choose: function(obj) {
       //预读本地文件示例,不支持ie8
       obj.preview(function(index, file, result) {
           var html = '<div class="img-content" id="content-' + index + '">';
           html += '<input type="hidden" name="paths[]" id="path-' + index + '">'
           html += '<img src="' + result + '" alt="' + file.name + '" class="img-100" id="img-' + index + '">';
           html += '<div style="width: 95px; margin:1px auto 0px; "><div class="layui-progress " lay-showpercent="yes" lay-filter="progress-' + index + '"> <div class="layui-progress-bar" lay-percent=""></div></div></div>';
           html += '<div class="img-cancel" id="cancel-' + index + '">x</div>';
           html += '</div>';
           $('#preview').append(html);
           //点击图片放大
           $('body').on('click', '#img-' + index, function(e) {
               layer.open({
                   type: 1,
                   title: false,
                   closeBtn: 1,
                   shadeClose: true,
                   area: ['500px', 'auto'],
                   content: "<img src=" + result + " />"
               });
           });
       });
       var files = obj.pushFile();
       var index, file, indexArr = [];

       //删除重复 selectArr 需要设置为全局参数并且不放在choose方法里
       for (let i = 0; i < selectArr.length; i++) {
          delete files[selectArr[i]];
       }
       //将index存放到数组中
       for (index in files) {
          indexArr.push(index);
       }
       for (let i = 0; i < indexArr.length; i++) {
          let file = files[indexArr[i]];

          if (file.size > 200 * 1024) {

              canvasDataURL(file, function(blob) {
                  var aafile = new File([blob], file.name, {
                      type: file.type
                  })

                  obj.upload(indexArr[i], aafile)
              })
          } else {
              obj.upload(indexArr[i], file)
          }

          selectArr.push(indexArr[i]);
       }
    },
    done: function(res, index, upload) {
        if (res.code == 200) {
            $("#path-" + index).attr("value", res.data.avatar)
            //删除按钮
            $('body').on('click', '#cancel-' + index, function() {
                $("#content-" + index).remove();
            });

        } else {
            $("#content-" + index).remove();
        }

    },
   progress: function(n, elem, res, index) {

       if (n == 100) {
           layer.msg('上传完毕', {
               icon: 1
           });
       }
       element.progress('progress-' + index, '100%'); //进度条复位
   },
   error: function(index, upload) {
       $("#content-" + index).remove();
   }
 })

参考 :
Layui 上传图片官方文档:https://www.layui.com/doc/modules/upload.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在uniapp中,将单选变为多选可以通过以下步骤实现: 1. 首先,需要在页面中将单选的选项改为多选的选项。可以使用`<checkbox>`标签来实现多选,将原来的`<radio>`标签改为`<checkbox>`标签。 2. 其次,需要在页面的data中添加一个数组来保存多选的选项值。可以在`data`中定义一个`selectedOptions`数组,用于存储选中的选项值。 3. 在`checkbox`标签中添加`@change`事件,将选中的选项值添加或删除到`selectedOptions`数组中,以此来实现多选功能。可以在`methods`中定义一个方法,当`checkbox`选项改变时触发该方法,在方法中判断选项值是否已经存在于`selectedOptions`数组中,如果存在则将其移除,如果不存在则将其添加到数组中。 4. 最后,可以在提交或保存数据时使用`selectedOptions`数组来获取所有选中的选项值。 综上所述,以上是将uniapp中的单选变为多选的步骤。通过修改页面中的选项标签、添加一个数组来保存选中的选项值,并在`checkbox`的`@change`事件中添加相应的处理逻辑,即可实现多选功能。<span class="em">1</span> #### 引用[.reference_title] - *1* [uniapp+unicloud 随机题库 在线答题 排行榜 专属用户 观众登录 判断题 多选 单选题](https://download.csdn.net/download/m0_59153175/86402733)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值