SoFunction
Updated on 2025-04-07

WeChat applet upload pictures

This article has shared the specific code for uploading pictures for WeChat applets for your reference. The specific content is as follows

//wxml <button class='button' bingtap="uploadSomeMsg">Upload</button>          &lt;view class="uploadImgBox"&gt;
            &lt;view class='smallImgBox'&gt;
              &lt;block wx:for="{{img_arr}}" wx:key="index"&gt;
                &lt;view class='logoinfo'&gt;
                  &lt;image class='logoinfo' mode="aspectFill" src='{{item}}' data-index="{{index}}" bindtap="previewImg"
                    bindlongpress="deleteImg" name="headimage" &gt;&lt;/image&gt;
                &lt;/view&gt;
              &lt;/block&gt;
              &lt;image bindtap='getLocalityImg' class='moreImg' src="../../images/"&gt;
              &lt;/image&gt;
            &lt;/view&gt;
            &lt;view&gt;
          &lt;/view&gt; 
&lt;/view&gt;
//wxss
.uploadImgBox {
  margin: 30rpx 0;
}

.logoinfo {
  height: 180rpx;
  width: 180rpx;
  margin: 10rpx ;
}

.smallImgBox {
  display: grid;
  grid-template-columns: repeat(3,1fr);
  grid-template-rows: repeat(2,180rpx);
  grid-gap:20rpx 10rpx;
}

.moreImg {
  border-radius: 10rpx;
  height: 180rpx;
  width: 180rpx;
  margin: 20rpx ;
}.button{  
 height: 90rpx;  
 width: 270rpx;  
 font-size: 38rpx;  
 background-color: rgba(146, 163, 45, 0.288);  
 font-weight: 600;  
 color: white;
 } 
 button::after {
  border: none;
} 
//js
Page({
  data: {
    img_arr: [], //Array of storing photos  },

///miniprogram/dev/api/network/upload/  WeChat mini-program upload file api  //Upload the picture to the server  uploadSomeMsg() {
    var that = this
    var adds = .img_arr;
    for (let i = 0; i &lt; .img_arr.length; i += 1) {
      ({
        url:'/upload', //For example only, non-real interface address        filePath: .img_arr[i],
        name: 'content',
        formData: {
          'user': adds
        },
        success: function (res) {
          (res, "Upload pictures")
          if (res) {
            ({
              title: 'Submitted and published!  ',
              duration: 3000
            });
          }
        }
      })
    }
  },

  //Get photos from local  getLocalityImg() {
    let that = this;
    if (.img_arr.length &lt; 5) {
      ({
        count: 5 - .img_arr.length, //The number of uploaded images When some pictures were uploaded before, total number - uploaded = remaining number (limited number of uploads)        sizeType: ['original', 'compressed'],  //You can specify original or compressed images, both are default        sourceType: ['album', 'camera'],        //Specify whether the image source is a camera or an album, and both are default     success(res) {
          (res, "------------------------------------------------------------------------------------------------------------------------------)

          const tempFiles =  //Array containing image size
          let answer = (item =&gt; {   //The uploaded image size is limited to 2M, and all images can be uploaded with less than 2M.            return  &lt;= 2000000
          })
    
          if (answer) {
            ({
              img_arr: .img_arr.concat(),
            })
          }else{
                  ({
                title:'Uploading images cannot be greater than 2M!',
                icon:'none'    
            })
          }

        }
      })

    } else {
      ({  //Tips for exceeding the number of pictures        title: 'Upload up to five pictures',
        icon: 'none',
        duration: 2000
      })

    }
  },

  //Delete photos and preview photos  deleteImg(e) {
    let that = this;
    let img_arr = .img_arr;
    let index = ;  //Get the index that long presses and deletes the picture    ({
      title: 'hint',
      content: 'Are you sure you want to delete this image?  ',
      success(res) {
        if () {
          // ('Click OK');          img_arr.splice(index, 1);
        } else if () {
          // ('Click to cancel');          return false;
        }
        ({
          img_arr: img_arr
        });
      }
    })
  },

  //Preview pictures  previewImg(e) {
    let index = ;
    let img_arr = .img_arr;
    ({
      current: img_arr[index],
      urls: img_arr
    })
  },


})

#Convert to base64 format

//1__Convert local upload pictures
//If you need to upload base64 format pictures to the backend, you can convert them like this when uploading pictures. Others are the same as those of ordinary interfaces uploading data.          //Convert result        let data=().readFileSync([0], "base64") 
//`data:image/png;base64,${data}`
// When uploading, you only need to add one before the conversion result: `data:image/png;base64,${data}` , which is the complete picture data.
  //2__Convert the server network image to base64    (url =&gt; {
          let newUrl = `/upload${url}` //You need to put a prefix to download the network picture
        (newUrl).then((res)=&gt;{
          .img_arr.push(res)
          ({
            img_arr:.img_arr
          })
          })

        })


  imageToBase(img) {
   return new Promise((resolve, reject)=&gt;{
      ({ //Download the picture first        url: img,
        success(res) {
          if ( === 200) {
            ({
              filePath:  //Select the relative path returned by the picture            })
            resolve()
          }
        }
      })
    })
  },

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.