【微信小程序】保存多张图片到本地相册 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('下载失败')
            }
          })
        }
      })
    }
  },
相关推荐
Vin__7 分钟前
微信小程序客服消息接收不到微信的回调
spring boot·微信小程序·小程序
计算机软件程序设计23 分钟前
vue和微信小程序处理markdown格式数据
前端·vue.js·微信小程序
lvbb661 小时前
微信小程序-二维码绘制
微信小程序·小程序
!win !1 小时前
我与微信审核的“相爱相杀”看个人小程序副业
微信小程序·个人开发·个人副业
狂团商城小师妹3 小时前
智慧废品回收小程序php+uniapp
大数据·微信·微信小程序·小程序·uni-app·微信公众平台
毕业设计-014 小时前
0083.基于springboot+uni-app的社区车位租赁系统小程序+论文
spring boot·小程序·uni-app
算是难了7 小时前
微信小程序-组件复用机制behaviors
微信小程序·小程序
说私域8 小时前
电商运营中私域流量的转化与变现:以开源AI智能名片2+1链动模式S2B2C商城小程序为例
人工智能·小程序·开源·流量运营
EasyNVR13 小时前
基于WebRTC与AI大模型接入EasyRTC:打造轻量级、高实时、强互动的嵌入式音视频解决方案
运维·服务器·微信·小程序·webrtc·p2p·智能硬件
我命由我1234513 小时前
微信小程序 - 自定义实现分页功能
前端·微信小程序·小程序·前端框架·html·html5·js