微信小程序保存圖片到相冊


1、經常會碰到這個場景:長按保存圖片到相冊。
小程序保存圖片到相冊需要獲取用戶的授權才可以保存成功,所以首先我們需要獲取小程序的授權狀態(拒絕/授權),授權狀態會被記錄在小程序緩存中,只有刪除小程序后才會被清除;如果已經拒絕或者授權都不會再展示授權彈窗,所以如果需要拒絕后再次打開授權,只能通過wx.openSetting來打開授權頁來設置,但是wx.openSetting只能在bindtap事件下觸發,所以需要去考慮如何處理長按的問題。授權成功后我們首先應該用wx.downloadFile去下載圖片,如果不下載直接調用wx.saveImageToPhotosAlbum會直接fail並且告訴你沒有這個文件。另外記得公眾平台配置download域名。

  saveImg (e) {
    let that = this
    let url = e.currentTarget.dataset.url
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.writePhotosAlbum'] == false) {
          wx.openSetting({
            success: (result)=>{
              console.log(result)
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success: function (res) {
                  console.log("授權成功");
                  that.loadImg(url)
                }    
              })              
            },
            fail: (err)=>{
              mainService.modal(err)
            }
          })
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: function (res) {
              console.log("授權成功");
              that.loadImg(url)
            }    
          })            
        }
      }
    })
  },
  loadImg (url) {
    wx.downloadFile({
      url,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            mainService.toast('保存成功')
          },
          fail: (err)=>{
            mainService.toast('保存失敗:', err)
          }                  
        })
      }
    })
  }

  


免責聲明!

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



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