【微信小程序】保存多张图片到本地相册 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('下载失败')
            }
          })
        }
      })
    }
  },
相关推荐
Emma歌小白2 天前
如何首次运行小程序后端
微信小程序
赣州云智科技的技术铺子2 天前
【一步步开发AI运动APP】十二、自定义扩展新运动项目1
微信小程序·小程序·云开发·智能小程序
2501_915918412 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张2 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
破无差2 天前
《赛事报名系统小程序》
小程序·html·uniapp
00后程序员张2 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬2 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
2501_915106322 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
亮子AI2 天前
【小程序】微信小程序隐私协议
微信小程序·小程序
weixin_177297220692 天前
短剧小程序系统开发:打造个性化娱乐新平台
小程序·娱乐·短剧