【非常全】微信小程序下载图片到相册,微信小程序自动获取分享图片到相册

背景:微信小程序用户分享时后端生成分享图片传给前端图片地址

主要用到的方法:

wx.downloadFile方法下载图片到本地并获取本地文件路径。
wx.openSetting 方法引导用户打开授权设置页面
wx.saveImageToPhotosAlbum 方法将临时文件保存到用户手机的相册中。

保存图片完整代码示例


    wx.downloadFile({
    
    
      url: '文件路径', 
      success (res) {
    
    
        if (res.statusCode === 200) {
    
    
          wx.saveImageToPhotosAlbum({
    
    
            filePath: res.tempFilePath,
            success(res) {
    
    
              
            wx.showToast({
    
    
              title: '保存成功'
            });
            },
            fail (err) {
    
    
              if (
                err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || 
                err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || 
                err.errMsg === "saveImageToPhotosAlbum:fail authorize no response"
              ) {
    
    
                wx.showModal({
    
    
                  title: '提示',
                  content: '需要您授权保存相册',
                  showCancel: false,
                  success: res=> {
    
    
                    wx.openSetting({
    
    
                      success(res) {
    
    
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
    
    
                          wx.showModal({
    
    
                            title: '提示',
                            content: '获取权限成功,再次点击分享即可保存',
                            showCancel: false,
                          })
                        } else {
    
    
                          wx.showModal({
    
    
                            title: '提示',
                            content: '获取权限失败,将无法保存到相册哦~',
                            showCancel: false,
                          })
                        }
                      },
                      fail(err) {
    
    
                        console.log("fail", err)
                      },
                      complete(res) {
    
    
                        console.log("finish", res)
                      }
                    })
                  }
                })
              } else if (err.errMsg === "saveImageToPhotosAlbum:fail cancel") {
    
    
                wx.showModal({
    
    
                  title: '提示',
                  content: '取消了保存分享图片,再次点击分享即可保存',
                  showCancel: false,
                })
              } else {
    
    
              }
            }
          })
        } else {
    
    
          util.hideToast()
          wx.showModal({
    
    
            title: '提示',
            content: "图片下载失败",
            showCancel: false,
          })
        }
      },
      fail () {
    
    
        util.hideToast()
        wx.showModal({
    
    
          title: '提示',
          content: "图片下载失败",
          showCancel: false,
        })
      }
    })

猜你喜欢

转载自blog.csdn.net/gjwgjw1111/article/details/134566101
今日推荐