小程序下载图片

367 阅读1分钟

方法一,推荐

  • 在image标签配置show-menu-by-longpress="true",提示文案,长按保存图片
<image class="userImg" src="{{detailData.qrcode}}" mode="widthFix" show-menu-by-longpress="true"></image>

方法二,点击按钮下载一张图片

  • 前提是图片链接域名在微信公众平台配置过

wxml

<view bindtap="preservationEvm">保存二维码</view>

<!-- 保存图片到本地授权失败 -->
<view class="wechart_mask" wx:if="{{is_wechart_mask}}">
    <view class="wechart_con">
        <view class="ui-content">
            <view class="cell-title">温馨提示</view>
            <view class="cell-content">"海鲜阿嫂"要保存图片,去设置允许访问相册</view>
        </view>
        <button open-type="openSetting" bindopensetting='getSetting'>确定</button>
    </view>
</view>

js

 data: {
    isKeFu:false,
    cartCount:'',
    is_wechart_mask:false
  },
  
preservationEvm(){//保存销售二维码
    var _this = this;
    console.log('保存')
    wx.downloadFile({
      url: '图片链接',
      success (res) {
        console.log(res,111)
        wx.saveImageToPhotosAlbum({&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;//保存到本地
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail(err){
            console.log(err,222)
            //用户点击了拒绝下载
            if(err.errMsg == "saveImageToPhotosAlbum:fail auth deny" || err.errMsg == "saveImageToPhotosAlbum:fail authorize no response"){
              _this.setData({
                is_wechart_mask:true
              })
            }else{
              wx.showToast({
                title: '保存失败',
                icon: 'fail',
                duration: 2000
              })
            }
          }
        })
      },
      fail (err){
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              console.log(settingdata)
              if (settingdata.authSetting['scope.writePhotosAlbum']) {
                console.log('获取权限成功,给出再次点击图片保存到相册的提示。')
              } else {
                console.log('获取权限失败,给出不给权限就无法正常使用的提示')
              }
            }
          })
        }
      }
    })
  },
  /**
   * 询问是否授权访问相册
   */
  getSetting(event) {
    var _this = this;
    this.setData({
      is_wechart_mask:false
    })
    // 对用户的设置进行判断,如果没有授权,即使用户返回到保存页面,显示的也是“去授权”按钮;同意授权之后才显示保存按钮
    if (!event.detail.authSetting['scope.writePhotosAlbum']) {
        wx.showModal({
            title: '温馨提示',
            content: '你关闭了访问相册的权限,无法保存,请允许访问相册',
            showCancel: false
        })
    } else {
        wx.showToast({
            icon: 'success',
            title: `授权成功`,
            success(res) {
                _this.preservationEvm()
            }
        })
    }
  },