美文网首页
小程序批量图片按选择顺序上传

小程序批量图片按选择顺序上传

作者: wangwing | 来源:发表于2019-04-12 13:07 被阅读0次

    wxml:

    <canvas canvas-id='attendCanvasId' class='myCanvas' style='width: {{canvasW + "px"}}; height: {{canvasH + "px"}}'></canvas>
    <button bindtap='takePhoto'>画布上传</button>
    
    <view wx:for="{{imgViewList}}" wx:key="{{index}}">
      <image mode='widthFix' src="{{item}}" />
    </view>
    

    js:

    // pages/canvas/index.js
    const MD5 = require('../../utils/uploadfile/MD5.js'); //图片名字转md5
    const app = getApp();
    
    Page({
      data: {
        imgViewList: []
      },
      onShow() {
        const token = wx.getStorageSync("jwt");
        wx.request({
          url: app.globalData.baseUrl + '/api/oss/frontend_sts_token',
          method: 'get',
          header: {
            'content-type': 'application/json',
            'Authorization': "Bearer " + token
          },
          success: res => {
            this.setData({
              sts_token_data: res.data.data
            })
          }
        })
      },
      takePhoto: function () {
        var that = this;
        //拍照、从相册选择上传
        wx.chooseImage({
          count: 9,  //这个是上传的最大数量,默认为9
          sizeType: ['compressed'],  //这个可以理解为上传的图片质量类型(官方给的),虽然没什么卵用,要不然还要我们自己写压缩做什么
          sourceType: ['album', 'camera'],  //这个是图片来源,相册或者相机
          success: function (res) {
            console.log(res)
            var tempFilePaths = res.tempFilePaths  //这个是选择后返回的图片列表
            that.getCanvasImg(0, 0, tempFilePaths);  //进行压缩
            wx.showLoading({
              title: '图片压缩上传中...',
              icon: 'none'
            })
          }
        });
      },
      //压缩并获取图片,这里用了递归的方法来解决canvas的draw方法延时的问题
      getCanvasImg: function (index, failNum, tempFilePaths) {
        var that = this;
        if (index < tempFilePaths.length) {
          wx.getImageInfo({
            src: tempFilePaths[index],
            success: imginfo=>{
              const radio = imginfo.height/imginfo.width;
              const imgurl = imginfo.path;
              that.setData({
                canvasW: 300,
                canvasH: 300 * radio
              },function(){
                setTimeout(() => {
                  const ctx = wx.createCanvasContext('attendCanvasId');
                  ctx.drawImage(imgurl, 0, 0, 300, 300 * radio);
                  ctx.draw(true, function () {
                    console.log(index)
                    index = index + 1;//上传成功的数量,上传成功则加1
                    wx.canvasToTempFilePath({
                      canvasId: 'attendCanvasId',
                      success: function success(res) {
                        that.uploadCanvasImg(res.tempFilePath, tempFilePaths.length);
                        setTimeout(() => {
                          that.getCanvasImg(index, failNum, tempFilePaths);
                        }, 500)
                      }, fail: function (e) {
                        failNum += 1;//失败数量,可以用来提示用户
                        that.getCanvasImg(index, failNum, tempFilePaths);
                      }
                    });
                  });
                }, 500)
              })          
            }
          })      
        }
      },
      //上传图片
      uploadCanvasImg: function (canvasImg, len) {
        var that = this;
        let sts_token_data = that.data.sts_token_data;
        let imgViewList = that.data.imgViewList;
        const imgName = canvasImg.split("tmp")[1].slice(1); // 截图图片名称部分
        const imgMd5Name = MD5.hexMD5(imgName);
        const aliyunFileKey = sts_token_data.dir + imgMd5Name + '.jpg'; //生成
        wx.uploadFile({
          url: sts_token_data.host, //文件服务器的地址
          filePath: canvasImg,
          formData: {
            'key': aliyunFileKey,
            'OSSAccessKeyId': sts_token_data.accessid,
            'policy': sts_token_data.policy,
            'signature': sts_token_data.signature,
            'success_action_status': '200',
          },
          name: 'file',
          success: function (res) {
            console.log(res)
            let url = app.globalData.imgUrl + aliyunFileKey
            // var json2map = JSON.parse(res.data);
            imgViewList.push(url);
            that.setData({
              imgViewList,
            });
            if (imgViewList.length == len){
              wx.hideLoading()
            }
          }
        })
      },
    })
    

    相关文章

      网友评论

          本文标题:小程序批量图片按选择顺序上传

          本文链接:https://www.haomeiwen.com/subject/lwqcwqtx.html