欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序保存多张图片的实现方法

程序员文章站 2022-08-28 08:23:43
前言 使用promise 队列,保存多张图片到手机相册 问题:有些手机会出现只能保存五张图片,报错信息:无法写入 promise需要好好学习 核心代码...

前言

使用promise 队列,保存多张图片到手机相册

问题:有些手机会出现只能保存五张图片,报错信息:无法写入

promise需要好好学习

核心代码

// pages/saveimgs/index.js
import { writephotosalbum } from '../../utils/util'
page({
 /**
  * 页面的初始数据
  */
 data: {
  list: [
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160008479.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160013201.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160015969.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160025498.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160031519.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160042689.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160108243.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190301160111756.jpg',
   'https://timgs.top1buyer.com/admin/special/special_img_20190304160141454.jpg'
  ],
  loading:false
 },

 /**
  * 生命周期函数--监听页面加载
  */
 onload: function(options) {},
 // 下载图片
 downloadimgs() {
  var _this = this
  // 获取保存到相册权限
  writephotosalbum(
   function success() {
    wx.showloading({
     title: '加载中',
     mask: true
    })
    // 调用保存图片promise队列
    _this
     .queue(_this.data.list)
     .then(res => {
      wx.hideloading()
      wx.showtoast({
       title: '下载完成'
      })
     })
     .catch(err => {
      wx.hideloading()
      console.log(err)
     })
   },
   function fail() {
    wx.showtoast({
     title: '您拒绝了保存到相册'
    })
   }
  )
 },
 // 队列
 queue(urls) {
  let promise = promise.resolve()
  urls.foreach((url, index) => {
   promise = promise.then(() => {
    return this.download(url)
   })
  })
  return promise
 },
 // 下载
 download(url) {
  return new promise((resolve, reject) => {
   wx.downloadfile({
    url: url,
    success: function(res) {
     var temp = res.tempfilepath
     wx.saveimagetophotosalbum({
      filepath: temp,
      success: function(res) {
       resolve(res)
      },
      fail: function(err) {
       reject(res)
      }
     })
    },
    fail: function(err) {
     reject(err)
    }
   })
  })
 }
})

微信小程序保存多张图片的实现方法

项目案例

git clone https://github.com/sunnie1992/soul-weapp.git

直接用微信小程序开发工具打开就可以看到案例了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。