微信小程序点击按钮将图片保存到手机

 SaveCard: function(e) {
    let that = this;
    console.log('保存');
    var imgSrc = e.currentTarget.dataset.img;
    //获取相册授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
              that.img(imgSrc)
            }
          })
        }else{
          that.img(imgSrc)
        }
      }
    })
  },
img: function (imgSrc){
    var imgSrc = imgSrc;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        console.log(res); //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            console.log(data);
            wx.showToast({
              title: '保存成功',
              duration: 2000
            })
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      title: '图片已保存',
                      icon:'none',
                      duration:2000
                    })
                    console.log('获取权限成功,给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败,给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
        })
      }
    })

  },

先授权,再保存

要实现微信小程序点击按钮分享图片至朋友圈,需要先引入微信官方提供的wx.shareTimeline() API。具体步骤如下: 1. 在小程序JS文件中编写分享功能的代码,例如: ``` // 点击分享按钮时触发 onShare: function () { wx.shareTimeline({ title: '分享标题', imageUrl: '图片URL' }) } ``` 2. 在wxml文件中添加一个分享按钮,例如: ``` <button bindtap="onShare">分享到朋友圈</button> ``` 3. 在小程序的app.json文件中添加权限声明: ``` { "mp-weixin": { "appid": "YOUR_APPID", "permission": { "scope.userLocation": { "desc": "你的位置信息将用于小程序位置接口的效果展示" }, "scope.writePhotosAlbum": { "desc": "你的相册将用于保存分享图片" } } } } ``` 4. 在用户点击分享按钮之前,需要获取用户授权访问相册的权限: ``` wx.authorize({ scope: 'scope.writePhotosAlbum', success: function () { // 用户已经同意授权 }, fail: function () { // 用户拒绝授权 } }) ``` 5. 在用户同意授权之后,可以使用wx.downloadFile() API下载图片保存到相册中: ``` wx.downloadFile({ url: '图片URL', success: function (res) { wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: function () { // 图片保存成功,可以调用分享接口 }, fail: function () { // 图片保存失败 } }) }, fail: function () { // 图片下载失败 } }) ``` 以上就是实现微信小程序点击按钮分享图片至朋友圈的基本步骤。需要注意的是,用户必须先授权访问相册的权限,才能够保存分享图片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值