【微信小程序】保存多张图片到本地相册 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_9159090628 分钟前
“绑定 HTTPS” 的工程全流程 从证书配置到真机验证与故障排查
网络协议·http·ios·小程序·https·uni-app·iphone
2501_915918412 小时前
iOS 混淆实战 多工具组合完成 IPA 混淆、加固与工程化落地(iOS混淆|IPA加固|无源码混淆|Ipa Guard|Swift Shield)
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者84 小时前
如何系统化掌握 iOS 26 App 耗电管理,多工具协作
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_915921435 小时前
运营日志驱动,在 iOS 26 上掌握 App 日志管理实践
android·macos·ios·小程序·uni-app·cocoa·iphone
小小王app小程序开发7 小时前
盲盒小程序核心玩法深度解析:一番赏、无限赏及商业逻辑拆解
小程序
skywalk81638 小时前
用Trae自动生成一个围棋小程序
人工智能·小程序
顾青8 小时前
微信小程序 VisionKit 实战(二):静态图片人脸检测与人像区域提取
前端·微信小程序
顾青8 小时前
微信小程序实现身份证识别与裁剪(基于 VisionKit)
前端·微信小程序
從南走到北9 小时前
西陆房产系统小程序
微信·微信小程序·小程序