[技術博客]使用wx.downloadfile將圖片下載到本地臨時存儲


目標

上一篇技術博客中,我們生成的海報中包含圖片,這些圖片是存儲到服務器上的,而canvas的drawimage函數只能讀取本地文件,因此我們在drawCanvas之前需要把服務器上的圖片下載到本地臨時存儲,這里選擇使用wx.downloadfile函數下載。

代碼展示

  //點擊分享按鈕之后觸發的大函數。主要是使用downloadfile下載所需圖像到本地,然后調用drawCanvas函數
  //由於異步加載不好控制,所以在這里進行串行下載 頭像、原海報,然后drawcanvas,不在其它地方預先下載
  genPoster: function () {
    if (_this.data.imagePath==""){
      wx.showLoading({
        title: '等待圖片下載',
      })
      //獲取用戶信息,下載頭像
      console.log('下面開始獲取用戶信息,主要為了得到頭像')
      util.$get('/users/current')
        .then((res) => {
          if (res.data.success) {
            _this.setData({
              userInfo: res.data.data.data
            })
            console.log("獲取的用戶信息為:")
            console.log(_this.data.userInfo)
            console.log("得到用戶信息,下面將這個頭像下載到臨時文件夾:")
            console.log(_this.data.userInfo.portrait_url)
            wx.downloadFile({
              url: _this.data.userInfo.portrait_url, //頭像資源
              success: function (res) {
                if (res.statusCode === 200) {
                  _this.setData({
                    touxiang: res.tempFilePath
                  })
                  console.log("成功下載頭像到臨時文件夾到:")
                  console.log(_this.data.touxiang);

                  console.log('下面將海報下載到臨時文件夾:')
                  console.log(_this.data.img_url);
                    wx.downloadFile({
                      url: _this.data.img_url, //原豎版海報
                      success: function (res) {
                        if (res.statusCode === 200) {
                          _this.setData({
                            poster_old: res.tempFilePath
                          })
                          console.log("成功下載原海報到臨時文件夾為:")
                          console.log(_this.data.poster_old)
                          wx.hideLoading();
                          _this.drawCanvas();
                        } else {
                          console.log("下載原海報返回的statusCode不是200")
                        }
                      },
                      fail: function (e) {
                        console.log('下載原海報失敗', e)
                      }
                    })
                  }
                } else {
                  console.log("下載頭像返回的statusCode不是200")
                }
              },
              fail: function (e) {
                console.log('下載頭像失敗', e)
              }
            })
          }
        })
    }
    else{
      console.log("之前畫過海報了,也就是圖片下載過了,現在直接drawCanvas,灰常快")
      _this.drawCanvas();
    }
  },

重點講解

首先需要向服務器發送請求,得到圖片資源的url,接着通過wx.downloadFile函數將url圖片下載到本地臨時存儲,wx.downloadFile的官方文檔是:https://developers.weixin.qq.com/miniprogram/dev/api/network/download/wx.downloadFile.html


這里尤其需要注意一個問題,由於是異步加載,所以如果需要下載多個圖片的話,建議串行進行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM