微信小程序一键保存多张图片

时间:2022-07-24
本文章向大家介绍微信小程序一键保存多张图片,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<view class="info">
    <block wx:for="{{dynamic_list}}" wx:for-item="item" wx:key="index">
        <view class="row">
            <view class="tulie" wx:for="{{item.file}}" wx:for-item="row" wx:key="key" wx:for-index="i">
                <image src="{{row.img_url}}"></image>
            </view>
        </view>
        <button data-index="{{index}}" bindtap="download">一键保存到相册</button>
        <view class="progress" wx:if="{{schedule}}">
            <progress percent="{{percent}}" duration="1" activeColor="#4aad8f" border-radius="10" stroke-width="12"
                show-info />
        </view>
    </block>
</view>
Page({
  data: {
    dynamic_list: [{
      file: [{
        img_url: 'https://sucai.suoluomei.cn/sucai_zs/images/20191123112141-2.png'
      }, {
        img_url: 'https://sucai.suoluomei.cn/sucai_zs/images/20191121151131-1.png'
      }, {
        img_url: 'https://sucai.suoluomei.cn/sucai_zs/images/20191121151131-2.png'
      }, {
        img_url: 'https://sucai.suoluomei.cn/sucai_zs/images/20191121100950-3.png'
      }, {
        img_url: 'https://sucai.suoluomei.cn/sucai_zs/images/20191121093322-2.png'
      }]
    }],
    percent: 0,
    schedule: false
  },

  // 下载图片到本地相册
  download(e) {
    let index = e.currentTarget.dataset.index
    this.getsave(0, this.data.dynamic_list[index].file.length, index)
  },
  getsave(i, length, index) {
    wx.showLoading({
      title: '下载中(' + (i + 1) + '/' + length + ')',
    })
    const downloadTask = wx.downloadFile({
      url: this.data.dynamic_list[index].file[i].img_url,
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (res) => {
            if (i + 1 == length) {
              wx.showToast({
                title: '保存成功',
              });
            }
            wx.hideLoading()
            if (++i < length) {
              this.getsave(i, length, index);
            }
          },
          fail: (err) => {
            wx.showToast({
              title: '保存图片失败',
              icon: 'none',
            })
          },
        })
      },
    })
    // 下载进度
    downloadTask.onProgressUpdate((res) => {
      console.log(res)
      if (res.progress > 0) {
        this.setData({
          schedule: true,
          percent: res.progress
        })
      }
      if (res.progress == 100) {
        this.setData({
          schedule: false
        })
      }
    })
  },
})