以前寫個一個版本的[多圖下載],重構進行了代碼升級讓代碼更加簡介
分爲兩步:
第一獲取保存到相冊權限
第二下載圖片
主要涉及兩個文件,index.js 和download.js
另外如今若是有圖片下載失敗也彈出下載完成後續須要優化javascript
/** * 獲取相冊權限 */
export function wxSaveAuth() {
return new Promise((resolve, reject) => {
wx.getSetting({
success(res) {
if (!res.authSetting['scope.writePhotosAlbum']) {
// 若是沒有寫入權限,則獲取寫入相冊權限
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
resolve()
},
fail(err) {
reject(err)
// 用戶拒絕受權
wx.showModal({
content: '檢測到您沒打開捷買士的相冊權限,是否去設置打開?',
confirmText: '確認',
cancelText: '取消',
success(res) {
if (res.confirm) {
wx.openSetting({
success: res => {}
})
}
}
})
}
})
} else {
resolve()
}
},
fail(e) {
reject(e)
}
})
})
}
/** * 多文件下載而且保存 * @param {Array} urls 網絡圖片數組 */
export function downloadImgs(urls) {
wx.showLoading({
title: '圖片下載中',
mask: true
})
const imageList = []
// 循環數組
for (let i = 0; i < urls.length; i++) {
imageList.push(getTempPath(urls[i]))
}
const loadTask = []
let index = 0
while (index < imageList.length) {
loadTask.push(
new Promise((resolve, reject) => {
// 將數據分割成多個promise數組
Promise.all(imageList.slice(index, (index += 8)))
.then(res => {
resolve(res)
})
.catch(err => {
reject(err)
})
})
)
}
// Promise.all 全部圖片下載完成後彈出
Promise.all(loadTask)
.then(res => {
wx.showToast({
title: '下載完成',
duration: 3000
})
})
.catch(err => {
wx.showToast({
title: `下載完成`,
icon: 'none',
duration: 3000
})
})
}
/** * * @param {String} url 單張網絡圖片 */
//下載內容,臨時文件路徑
function getTempPath(url) {
return new Promise((resolve, reject) => {
wx.downloadFile({
url: url,
success: function(res) {
var temp = res.tempFilePath
wx.saveImageToPhotosAlbum({
filePath: temp,
success: function(res) {
return resolve(res)
},
fail: function(err) {
reject(url + JSON.stringify(err))
}
})
},
fail: function(err) {
reject(url + JSON.stringify(err))
}
})
})
}
複製代碼
// pages/save-imgs/index.js
import { wxSaveAuth, downloadImgs } from '../../utils/download'
Page({
/** * 頁面的初始數據 */
data: {
urls: [
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4',
'https://avatars0.githubusercontent.com/u/35954879?s=120&v=4'
]
},
/** * 生命週期函數--監聽頁面加載 */
onLoad: function(options) {},
download() {
// 獲取保存到相冊權限
wxSaveAuth().then(res => {
// 保存多張圖片到相冊
downloadImgs(this.data.urls)
})
},
})
複製代碼
github地址java
git clone https://github.com/sunnie1992/sol-weapp.git複製代碼
掃描添加下方的微信並備註 Sol 加交流羣,交流學習,及時獲取代碼最新動態。git
若是對你有幫助送我一顆小星星(づ ̄3 ̄)づ╭❤~github