Solve the problem that the image component of the WeChat applet cannot carry cookies

Solve the problem that the image component of the WeChat applet cannot carry cookies

problem background

Many projects will need to access the server to obtain network pictures. This article will introduce how the WeChat applet loads pictures that require cookies.

problem analysis

In many projects, the image server generally performs cookie login-related verification. On the client side, using components such as glide on the Android side for remote image loading can directly transfer cookies, but the image component of the applet cannot directly transfer Cookies are used to load images, so special handling is required.
Since the applet does not automatically carry cookies like the web page after logging in, you need to use the wx.downloadFile() method provided by the applet to download the file to the local, and then assign it to the src attribute of the image.
For related API introduction, refer to the official website documentation, https://developers.weixin.qq.com/miniprogram/dev/api/network/download/wx.downloadFile.html, the sample code is as follows:

wx.downloadFile({
  url: 'https://example.com/audio/123', //仅为示例,并非真实的资源
  success (res) {
    // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
    if (res.statusCode === 200) {
      wx.playVoice({
        filePath: res.tempFilePath
      })
    }
  }
})

problem solved

Not much to say, just go to the code.

let flieName = `${new Date().valueOf()}.png`
      wx.downloadFile({
        header: {
          'cookie': wx.getStorageSync("cookie"),
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        url: data[i].url,
        filePath:`${wx.env.USER_DATA_PATH}/${flieName}`,
        success(res) {
          console.log('res show')
          console.log(res)
          if (res.statusCode == 200) {
            data[i].picture = res.filePath
          }
        },
        fail(res) {
          console.log(res)
        }
      })

conclusion of issue

This article introduces how the WeChat applet loads pictures that require cookies. Interested students can further study in depth.

Guess you like

Origin blog.csdn.net/weixin_39033300/article/details/130552688