微信小程序 wx.chooseImage上傳圖片 base64地址 封裝

先說下思路:

  1. 上傳圖片按鈕觸發事件,調用wx.chooseImage方法,返回本地的臨時路徑
  2. 遍歷臨時路徑,讀取文件管理器wx.getFileSystemManager的本地文件內容.readFile,根據臨時地址獲取base64轉碼

貼上主要代碼,封裝的是一個mpvue的項目上傳圖片組件。

值得注意的是:步驟2儲存的base64地址若是過長可能會出現傳參出現問題,因此仍是推薦在父組件執行步驟2,獲取base64碼,或者每選擇一張圖片上傳一次到後臺。反正代碼和邏輯都在這,怎麼修改都行啦html

1.選擇圖片,保存臨時地址vue

// 選擇圖片
    chosseImg() {
      const that = this;
      let num = 8; //上傳的圖片最大數量
        wx.chooseImage({
          count: num - that.imgPathArr.length, //最大圖片數量=最大數量-臨時路徑的數量
          sizeType: ["compressed"], //圖片尺寸 original--原圖;compressed--壓縮圖
          sourceType: ["album", "camera"], //選擇圖片的位置 album--相冊選擇, 'camera--使用相機 success: res => { const imgPathArr = this.imgPathArr; this.imgPathArr = []; this.imgPathArr = imgPathArr.concat(res.tempFilePaths); console.log(res.tempFilePaths, "base"); that.updateImg(); } }); }, 複製代碼

2.根據臨時路徑,獲取圖片base64碼。git

//根據臨時路徑,獲取圖片base64碼。
    updateImg() {
      const that = this;
      this.imgBase = [];
      // 根據臨時路徑數組imgPathArr獲取base64圖片
      this.imgPathArr.map(item=>{
        //異步方法
        wx.getFileSystemManager().readFile({
          filePath: item, //選擇圖片返回的相對路徑
          encoding: "base64", //編碼格式
          success: res => {
            //成功的回調
            that.imgBase.push({
              PicUrl: "data:image/png;base64," + res.data.toString()
            });
            // 最後一張圖片時,返回數據
            if(this.imgBase.length===this.imgPathArr.length){
            this.$emit("upImgs", this.imgBase);
            }
          }
        });
        
        //同步方法
        //let imgItem = wx.getFileSystemManager().readFileSync(item, "base64");
        //that.imgBase.push({
        //    PicUrl: "data:image/png;base64," + imgItem.toString()
        //});
        // 最後一張圖片時,返回數據
        //if(this.imgBase.length===this.imgPathArr.length){
        //this.$emit("upImgs", this.imgBase);
        //}
        
      })
    }
複製代碼

最後放上封裝的組件地址 github.com/Ansxu/upimg…github

相關文章
相關標籤/搜索