1. 程式人生 > >小程式快取個人頭像

小程式快取個人頭像

開發小程式專案,有時候要對個人資訊的頭像資訊進行快取。

頁面頭像結構(這裡需要考慮如果沒有頭像時,該怎麼顯示。我使用的是男生使用50%圓角的藍色塊,女生使用50%圓角的粉色塊。在藍、粉塊居中顯示使用者名稱稱的第一個字)

<view class="img-container">
    <image wx:if="{{hidden}}" class="head-img" src="{{photoPath}}"></image>
</view>
           

1. 首先從介面獲取頭像資訊,使用wx.downloadFile下載檔案資源到本地,使用wx.saveFile儲存檔案到本地

wx.downloadFile({
          url: '', // 網路返回的圖片地址
          fail:function(err){
            console.log(err)
          },
          success: function (res) {
            // console.log(res.tempFilePath, "下載路徑");
            wx.saveFile({
              tempFilePath: res.tempFilePath,
              success: function (res) {
                // console.log(res.savedFilePath,"儲存路徑");
                wx.setStorageSync("photoPath", res.savedFilePath)
              }
            })
          }
        })

2. 再次進入個人中心時,需要判斷本地是否有快取在,如果有則先載入快取的頭像,再去請求介面。 

if (wx.getStorageSync("photoPath")){
      wx.getImageInfo({
        src: wx.getStorageSync("photoPath"),
        success: function (res) {
          me.setData({
            photoPath: res.path
          })
        }
      })
    }