【微信小程序】保存多张图片到本地相册 wx.saveImageToPhotosAlbum

这里写目录标题

微信小程序检测是否有存储权限

wx.getSetting

上传前判断是否开启存储权限,如果不检测直接上传会出现fail的情况

javascript 复制代码
var _this = this
wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          // 已获得存储相册授权
          _this.writeInImg()
        }
        else {
          // 未获得存储相册授权
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: () => {
              wx.openSetting({
                success(settingdata) {
                //再进行图片上传操作
                  _this.writeInImg()
                }
              })
            }
          })
        }
      }
    })

图片上传

从HTML中提取img标签的src属性

后端返回一个字符串,内容是标签,img,需要截取出src中的图片链接,

javascript 复制代码
 getImage(){
    const srcRegex = /<img\s+(?:[^>]*?\s+)?src\s*=\s*(["'])((?:[^\1"]|\\\1|.)*?)\1/g
    const result = [...this.data.details.goods_content.matchAll(srcRegex)]
    const imgSrcs = result.map(v => v[2])
    return imgSrcs[0]
  },

多图片下载

javascript 复制代码
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [
    	'https://tys.zye.com/upload/1/common/20231110/207169967318.jpg',
    	'https://tys.zye.com/upload/1/common/20231110/207169967318.jpg',
    	'https://tys.zye.com/upload/1/common/20231110/207169967318.jpg',	
    ],
}

writeInImg() {
    let imgList = this.data.imgList 
    let imglength = imgList.length; // 要下载的总条数
    let index = 0;
    
    wx.showLoading({
      title: '加载中',
    })
    for (let i = 0; i < imgList.length; i++) {
      wx.downloadFile({
        url: imgList[i],
        success: function(res) {
          var temp = res.tempFilePath
          wx.saveImageToPhotosAlbum({
            filePath: temp,
            success(res) {
              index++;
              // 全部下载完后触发
              if (index == imglength) {
                wx.hideLoading();
                wx.showToast({
                  title:'下载成功',
                  icon:'success',
                  duration:2000
                })
              }

            },
            fail(err){
              wx.hideLoading();
              console.log('下载失败')
            }
          })
        }
      })
    }
  },
相关推荐
2501_9159090629 分钟前
Flutter 应用怎么加固,多工具组合的工程化实战(Flutter 加固/Dart 混淆/IPA 成品加固/Ipa Guard + CI)
android·flutter·ios·ci/cd·小程序·uni-app·iphone
千寻技术帮2 小时前
50013_基于微信小程序的校园志愿者系统
mysql·微信小程序·springboot·文档·ppt
2501_915909064 小时前
深入理解HTTPS和HTTP的区别、工作原理及安全重要性
安全·http·ios·小程序·https·uni-app·iphone
汤姆yu4 小时前
基于微信小程序的民宿预定系统
微信小程序·小程序·民宿预定
小小王app小程序开发6 小时前
淘宝扭蛋机小程序:电商娱乐化赛道的机遇挖掘与风险防控
小程序·娱乐
说私域6 小时前
基于开源AI智能名片链动2+1模式与S2B2C商城小程序的商家活动策略研究
人工智能·小程序
低代码布道师6 小时前
医疗小程序07设置默认卡
低代码·小程序
黑夜世界13 小时前
微信小程序map组件聚合簇样式自定义
微信小程序·小程序
菠菠萝宝15 小时前
【AI应用探索】-10- Cursor实战:小程序&APP - 下
人工智能·小程序·kotlin·notepad++·ai编程·cursor
qq_124987075315 小时前
基于微信小程序的茶叶茶具销售和管理系统(源码+论文+部署+安装)
微服务·微信小程序·小程序·毕业设计