前言
使用promise 隊(duì)列,保存多張圖片到手機(jī)相冊(cè)
問題:有些手機(jī)會(huì)出現(xiàn)只能保存五張圖片,報(bào)錯(cuò)信息:無法寫入
promise需要好好學(xué)習(xí)
核心代碼
// pages/saveImgs/index.js import { writePhotosAlbum } from '../../utils/util' Page({ /** * 頁面的初始數(shù)據(jù) */ 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_201903011600298.jpg', 'https://timgs.top1buyer.com/admin/special/special_img_20190301160031519.jpg', 'https://timgs.top1buyer.com/admin/special/special_img_201903011600426.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_201903041601414.jpg' ], loading:false }, /** * 生命周期函數(shù)--監(jiān)聽頁面加載 */ onLoad: function(options) {}, // 下載圖片 downloadImgs() { var _this = this // 獲取保存到相冊(cè)權(quán)限 writePhotosAlbum( function success() { wx.showLoading({ title: '加載中', mask: true }) // 調(diào)用保存圖片promise隊(duì)列 _this .queue(_this.data.list) .then(res => { wx.hideLoading() wx.showToast({ title: '下載完成' }) }) .catch(err => { wx.hideLoading() console.log(err) }) }, function fail() { wx.showToast({ title: '您拒絕了保存到相冊(cè)' }) } ) }, // 隊(duì)列 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) } }) }) } })
項(xiàng)目案例
github地址
git clone https://github.com/sunnie1992/soul-weapp.git
直接用微信小程序開發(fā)工具打開就可以看到案例了
Copyright ? 2019- 91gzw.com 版權(quán)所有 湘ICP備2023023988號(hào)-2
違法及侵權(quán)請(qǐng)聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務(wù)所王興未律師提供法律服務(wù)