欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-01-27 10:39:32|栏目:JavaScript代码|点击:

前言

使用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)
    }
   })
  })
 }
})

项目案例

github地址

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

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

上一篇:来访统计

栏    目:JavaScript代码

下一篇:JavaScript实现垂直向上无缝滚动特效代码

本文标题:微信小程序保存多张图片的实现方法

本文地址:http://www.codeinn.net/misctech/52042.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有