开发小程序项目,有时候要对个人信息的头像信息进行缓存。

页面头像结构(这里需要考虑如果没有头像时,该怎么显示。我使用的是男生使用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          })        }      })    }

 

TAG标签: 微信小程序微信头像下载

http://www.xiaochengxub.com/read-106958.html