【微信小程序】保存多张图片到本地相册 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('下载失败')
            }
          })
        }
      })
    }
  },
相关推荐
demo007x7 小时前
如何提高 AI 做小程序的效率?
微信小程序·ai编程·claude
2601_952013768 小时前
新麦同城到家预约上门小程序V3全开源版 vueadmin+unipp开源前端+小程序端
小程序
土土哥V_araolin10 小时前
双迪大健康模式系统开发
小程序·个人开发·零售
2501_9160074710 小时前
HTTPS 抓包的流程,代理抓包、设备数据线直连抓包、TCP 数据分析
网络协议·tcp/ip·ios·小程序·https·uni-app·iphone
css在哪里12 小时前
小程序版 Three.js 入门 Demo(完整可运行)
3d·小程序·threejs
游戏开发爱好者812 小时前
React Native iOS 代码如何加密,JS 打包 和 IPA 混淆
android·javascript·react native·ios·小程序·uni-app·iphone
CHU72903513 小时前
社区生鲜买菜小程序前端功能版块设计及玩法介绍
前端·小程序
2501_9159184113 小时前
iOS mobileprovision 描述文件管理,新建、下载和内容查看
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张13 小时前
iOS 应用程序使用历史记录和耗能记录怎么查?
android·ios·小程序·https·uni-app·iphone·webview
吴声子夜歌14 小时前
小程序——WeUI组件
小程序