微信小程序 一键下载所有图片和视频
function downloadFiles(type, urls) {
checkAuth(() => {
wx.showLoading({
title: '正在下载',
mask: true
})
for (let i = 0; i < urls.length; i++) {
downloadSaveFile(
urls[i],
);
}
})
}
function downloadSaveFile(url, successc) {
let isimg = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf, jpeg'.includes(url.split('.').slice(-1))
if (isimg) {
wx.downloadFile({
url: url,
success: res => {
if (res.statusCode === 200) {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: res => {
wx.showToast({
title: '保存成功',
icon: "none"
})
},
fail: res => {
wx.showToast({
title: '保存失败',
icon: "none"
})
}
})
}
}
})
} else {
wx.downloadFile({
url: url,
success: res => {
if (res.statusCode === 200) {
wx.saveVideoToPhotosAlbum({
filePath: res.tempFilePath,
success: res => {
wx.showToast({
title: '保存成功',
icon: "none"
})
},
fail: res => {
wx.showToast({
title: '保存失败',
icon: "none"
})
}
})
}
}
})
}
}
function checkAuth(gotc) {
wx.showLoading({
title: '检查授权情况',
mask: true
})
wx.getSetting({
success(res) {
wx.hideLoading();
if (!res.authSetting['scope.writePhotosAlbum']) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success() {
gotc && gotc();
},
fail() {
wx.showModal({
title: '',
content: '保存到系统相册需要授权',
confirmText: '授权',
success(res) {
if (res.confirm) {
wx.openSetting({
success(res) {
if (res.authSetting['scope.writePhotosAlbum'] === true) {
gotc && gotc();
}
}
})
}
},
fail() {
wx.showToast({
title: '打开设置页失败',
icon: 'none',
})
}
})
}
})
} else {
gotc && gotc();
}
},
fail() {
wx.hideLoading();
wx.showToast({
title: '获取授权失败',
icon: 'none',
})
}
})
}
module.exports = {
downloadFiles
};