微信SDK实现多张图片上传

时间:2022-07-24
本文章向大家介绍微信SDK实现多张图片上传,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

必须要先wx.config配置,jsApiList里面引入我们需要的微信Api

    wx.config({
        debug: false,
        appId: 'appId',
        timestamp: 'timestamp',
        nonceStr: 'nonceStr',
        signature: 'signature',
        jsApiList: ['chooseImage', 'getLocalImgData']
    });

核心Js代码

   getupload() {
          wx.chooseImage({
              count: 9,
              sizeType: ['original', 'compressed'],
              sourceType: ['album', 'camera'],
              success: (res) => {
                  this.getpublish(res.localIds, 0)
              }
          });
      },
    getpublish(list, i) {
           wx.getLocalImgData({
               localId: list[i],
               success: (res) => {
                   var localData = res.localData
                   //将base64转换为blob
                   let base = atob(localData.substring(localData.indexOf(',') + 1));
                   let length = base.length;
                   let url = new Uint8Array(length);
                   while (length--) {
                       url[length] = base.charCodeAt(length);
                   }
                   let file = new File([url], 'a.jpg', {
                       type: 'image/jpg'
                   })
                   var formData = new FormData();
                   formData.append("file", file);
                   formData.append("key", "qqq");
                   axios({
                       method: "post",
                       url: "http://uploadFile",
                       data: formData
                   })
                       .then((res) => {
                       	   //采用递归上传
                           if (res.data.status == 200) {
                               this.file_list.push(res.data.info.url)
                               if (i + 1 == list.length) {
                                   console.log('上传成功')
                               }
                               if (++i < list.length) {
                                   this.getpublish(list, i);
                               }
                           } else {
                               alert('上传失败')
                           }
                       })
               }
           });
       },