zoukankan      html  css  js  c++  java
  • 微信小程序保存图片到相册

    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)
              }                  
            })
          }
        })
      }
    

      

  • 相关阅读:
    0455分发饼干 Marathon
    0078子集 Marathon
    python 实现JWT Marathon
    0376摆动序列 Marathon
    0216.组合总和 III Marathon
    028实现strStr() Marathon
    0738单调递增的数字 Marathon
    0051N皇后 Marathon
    0047全排列II Marathon
    0037解数独 Marathon
  • 原文地址:https://www.cnblogs.com/muzs/p/13666384.html
Copyright © 2011-2022 走看看