需求
微信小程序中将线上视频下载到用户手机相册
一、代码片段
以下代码可直接cv 当前开发基础库 2.16.0
download() {
const _this = this
let fileName = new Date().valueOf()
let nowActive = _this.data.videoList[_this.data.nowActiveIndex] //这里当前视频行数据的的对象 根据自己业务修改
console.log(wx.env, "userPath")
wx.showLoading({
title: '正在下载',
mask: true
})
wx.downloadFile({
url: _this.data.filePrefix + nowActive.vurl, // 视频地址 根据自己业务修改
filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
success: (res) => {
console.log(res)
wx.saveVideoToPhotosAlbum({
filePath: res.filePath,
success: (ress) => {
wx.showToast({
title: '下载成功',
icon: 'success'
})
//删除临时文件
var fileManager = wx.getFileSystemManager(); //全局唯一的文件管理器
fileManager.unlink({ //删除
filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
success: function (resf) {
console.log('unlink', resf)
}
})
},
fail: (ress) => {
wx.hideLoading()
console.log(ress)
if(ress.errMsg == 'saveVideoToPhotosAlbum:fail auth deny'){
wx.showModal({
title: '提示',
content: '需要您授与xxx"相册"权限', // 提示语, 根据业务修改
showCancel: false,
success: function(c) {
//调起客户端小程序设置界面,返回用户设置的操作结果。
wx.openSetting({
success: function(settingdata) {
if(settingdata.authSetting['scope.writePhotosAlbum']){
wx.showModal({
title: "提示",
content: "获取权限成功,再次点击下载即可保存",
showCancel: false
})
}else{
wx.showModal({
title: "提示",
content: "获取权限失败,将无法保存到相册",
showCancel: false
})
}
}
})
}
})
}
}
})
}
})
},
二、如何使用
注意上文代码中注释的部分, 一共三处需要修改, 注意根据自己业务需求修改 !
直接把上文方法绑定到按钮上 或自行根据需求修改
我们已经做了一些错误的拦截, 基础业务跑起来该有的都有的, 放心用
总结
核心方法
- wx.env
- wx.downloadFile
- wx.saveVideoToPhotosAlbum
- wx.getFileSystemManager