首先先用class封装一个Toast提示
// 一些弹窗
class Toast{
constructor(title,icon="success",duration=1300,mask=true) {
this.title = title
this.icon = icon
this.duration = duration
this.mask = mask
}
// 消息提示框:自动消失
showtoast(){
uni.showToast({
title: this.title,
icon:this.icon,
duration: this.duration,
mask:this.mask
});
}
// 消息提示框,手动消失
showloading(){
uni.showLoading({
title: this.title,
mask:true
});
}
// 轻提示
}
export default Toast
然后开始封装保存图片downloadImg.js
import toast from './toast.js'
export default function downloadImg(url){
uni.showLoading({
title: '正在下载',
mask: true
})
console.log(url)
let that = this;
uni.getImageInfo({
src: url,
success(res) {
console.log(res.path)
uni.saveImageToPhotosAlbum({
filePath: res.path,
success(res) {
new toast("已保存至相册").showtoast()
},
fail(err) {
console.log(err);
uni.hideLoading();
uni.showModal({
title: '保存图片至相册',
content: '需要获取您的相册权限,请确认授权',
success: function(res) {
if (res.cancel) {
uni.showToast({
title: '获取相册权限失败',
icon: 'none',
duration: 2000
})
} else if (res.confirm) {
uni.showLoading({
title: '打开设置',
mask: true
})
uni.openSetting({
success: function(data) {
uni.hideLoading();
new toast("请重新点击下载原图").showloading()
}
})
}
}
})
}
})
},
fail(err) {
console.log(err);
new toast("下载失败,请重试").showloading()
}
})
}
项目中如何使用呢???
import downloadImg from '../../../public/downloadImg.js'
downloadImg(url) 调用即可
url是图片的地址
github上有详细的教程
github项目地址:https://github.com/lsh555/TmUniapp