微信小程序保存在线图片和视频以及base64字符串案例代码
Base64图片的下载
js
// pages/test/test2/test2.js
Page({
/**
* 页面的初始数据
*/
data: {
imageurl: ''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
console.log(options);
let url = options.url // 这个url就是一个base64字符串,data:image/png;base64,...开头
// 分片
let quarterLength = Math.ceil(url.length / 4);
let str1 = url.substring(0, quarterLength);
let str2 = url.substring(quarterLength, quarterLength * 2);
let str3 = url.substring(quarterLength * 2, quarterLength * 3);
let str4 = url.substring(quarterLength * 3); // 将base64字符串拆分成四份,解决数据传输长度过长问题
this.setData({
imageurl: (str1 + str2 + str3 + str4).replace(/[\r\n]/g, '') // 这个base64不能有换行符之类的,不然页面展示不了,这里进行一下处理
})
},
// 将base64字符串转成图片文件
base64ToImageFile(base64Data, callback) {
const fs = wx.getFileSystemManager();
const timestamp = new Date().getTime();
const filePath = `${wx.env.USER_DATA_PATH}/image_${timestamp}.png`;
// 去掉前缀
base64Data = base64Data.replace(/^data:image\/png;base64,/, '');
try {
const buffer = wx.base64ToArrayBuffer(base64Data);
fs.writeFile({
filePath: filePath,
data: buffer,
encoding: 'binary',
success: () => {
callback(filePath);
},
fail: (err) => {
console.error('保存Base64图片到本地失败:', err);
}
});
} catch (e) {
console.error('Base64转换失败:', e);
}
},
// 保存图片
saveBase64ImageToPhotosAlbum(base64Data) {
wx.showLoading({
title: '正在保存...',
})
//视频保存到相册跟图片保存到相册使用方式相同
//下载到本地,判断是否拥有权限
wx.getSetting({
withSubscriptions: true,
success: res => {
console.info(res.authSetting);
if (res.authSetting['scope.writePhotosAlbum']) {
this.base64ToImageFile(base64Data, (filePath) => {
wx.saveImageToPhotosAlbum({
filePath: filePath,
success: (res) => {
wx.hideLoading()
setTimeout(()=>{
wx.showToast({
title: '保存成功',
icon: 'success',
});
},500)
setTimeout(()=>{
wx.navigateBack()
},2500)
},
fail: (err) => {
wx.hideLoading()
setTimeout(()=>{
wx.showToast({
title: '保存失败',
icon: 'error'
});
},500)
setTimeout(()=>{
wx.navigateBack()
},2500)
console.error('保存图片到相册失败:', err);
}
});
});
} else {
wx.hideLoading()
wx.showModal({
cancelColor: 'cancelColor',
title: '提示',
content: '请开启相册访问权限',
success: res => {
if (res.confirm) {
wx.openSetting({
withSubscriptions: true,
})
} else if (res.cancel) {
setTimeout(()=>{
wx.showToast({
title: '保存失败',
icon: 'error'
});
},500)
setTimeout(()=>{
wx.navigateBack()
},2500)
console.log('点击了取消,返回上层');
}
}
})
}
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示(页面显示就执行下载逻辑,不过还是建议放到onLoad生命周期内)
*/
onShow() {
// 这个base64不能有换行符之类的imageurl刚好在存数据时把空格去掉了
this.saveBase64ImageToPhotosAlbum(this.data.imageurl.split(',')[1])
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})在线图片下载到相册(包含进度条)
js
// 下载封面到相册
downloadImageClick(e) {
//视频保存到相册跟图片保存到相册使用方式相同
//下载到本地,判断是否拥有权限
wx.getSetting({
withSubscriptions: true,
success: res => {
console.info(res.authSetting);
if (res.authSetting['scope.writePhotosAlbum']) {
const downloadTask = wx.downloadFile({
url: e.currentTarget.dataset.url, // 这个就是在线图片链接
success: res => {
//保存到相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: res => {
console.info(res);
wx.showToast({
title: "保存成功",
icon: 'success'
});
},
fail: res => {
wx.showToast({
title: '保存失败',
icon: error
})
}
})
},
fail(err){
wx.showToast({
title: '保存失败,建议复制链接请前往浏览器下载,或者重新生成视频',
icon:"none"
})
}
});
// 监听下载进度更新事件
downloadTask.onProgressUpdate((res) => {
// console.log('下载进度', res.progress);
// console.log('已下载的数据长度', res.totalBytesWritten);
// console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
// 更新下载进度显示
wx.showLoading({
title: `下载中... ${res.progress}%`,
});
});
} else {
wx.showModal({
cancelColor: 'cancelColor',
title: '提示',
content: '请开启相册访问权限',
success: res => {
if (res.confirm)
wx.authorize({
scope: 'scope.writePhotosAlbum', // 请求写入相册的权限
success() {
console.log('已获得权限');
// 这里可以执行需要相册权限的操作,例如保存图片到相册
},
fail() {
wx.showModal({
title: '提示',
content: '需要您授权访问相册',
showCancel: false,
success: modalRes => {
if (modalRes.confirm) {
wx.openSetting({
withSubscriptions: false // 不需要订阅消息
});
}
}
});
}
});
}
})
}
}
})
},在线视频下载到相册(包含进度条)
第一版
js
//下载视频到相册
downloadVideoClick(e) {
console.log(e.currentTarget.dataset.url);
//视频保存到相册跟图片保存到相册使用方式相同
//下载到本地,判断是否拥有权限
wx.getSetting({
withSubscriptions: true,
success: res => {
console.info(res.authSetting);
if (res.authSetting['scope.writePhotosAlbum']) {
const downloadTask = wx.downloadFile({
url: e.currentTarget.dataset.url, // 这个就是在线视频链接
success: res => {
//保存到相册
wx.saveVideoToPhotosAlbum({
filePath: res.tempFilePath,
success: res => {
console.info(res);
wx.showToast({
title: "保存成功",
icon: 'success'
});
},
fail: res => {
wx.showToast({
title: '保存失败',
icon: "error"
})
}
})
},
fail(err){
console.log(err);
wx.showToast({
title: '保存失败,建议复制链接请前往浏览器下载,或者重新生成视频',
icon:"none"
})
}
});
// 监听下载进度更新事件
downloadTask.onProgressUpdate((res) => {
// console.log('下载进度', res.progress);
// console.log('已下载的数据长度', res.totalBytesWritten);
// console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
// 更新下载进度显示
wx.showLoading({
title: `下载中... ${res.progress}%`,
});
});
} else {
wx.showModal({
cancelColor: 'cancelColor',
title: '提示',
content: '请开启相册访问权限',
success: res => {
if (res.confirm)
wx.openSetting({
withSubscriptions: true,
})
}
})
}
},
fail(err){
console.log(err);
}
})
},第二版
js
// 保存视频
saveVideo() {
if (!this.data.videoUrl) {
message.showToast('视频不存在')
return
}
const that = this;
// 1. 先检查权限状态
wx.getSetting({
withSubscriptions: true,
success: async (res) => {
console.info('当前权限状态:', res.authSetting)
const hasPermission = res.authSetting['scope.writePhotosAlbum']
// 2. 已有权限,直接保存
if (hasPermission === true) {
that.downloadAndSaveVideo()
return
}
// 3. 从未询问过,主动申请权限
if (hasPermission === undefined) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: () => {
console.log('权限申请成功')
that.downloadAndSaveVideo()
},
fail: (authErr) => {
console.log('权限申请失败或被拒绝', authErr)
that.showPermissionModal('请开启相册访问权限')
}
})
return
}
// 4. 用户已明确拒绝,提示去设置页面
if (hasPermission === false) {
that.showPermissionModal('请开启相册访问权限')
}
},
fail: (err) => {
console.log('权限检查失败', err)
wx.showToast({
title: '权限检查失败,请重试',
icon: 'none'
})
}
})
},
// 下载并保存视频(抽离为单独方法)
downloadAndSaveVideo() {
const that = this
wx.showLoading({
title: '准备下载...',
})
const downloadTask = wx.downloadFile({
url: that.data.videoUrl,
success: (res) => {
wx.hideLoading()
if (res.statusCode === 200) {
// 保存到相册
wx.saveVideoToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
})
},
fail: (saveErr) => {
console.log('保存到相册失败', saveErr)
wx.showToast({
title: '保存失败,请重试',
icon: 'none'
})
}
})
} else {
wx.showToast({
title: '下载失败',
icon: 'none'
})
}
},
fail: (downloadErr) => {
wx.hideLoading()
console.log('下载失败', downloadErr)
wx.showToast({
title: '下载失败,建议复制链接在浏览器中打开',
icon: 'none'
})
}
})
// 监听下载进度
downloadTask.onProgressUpdate((res) => {
wx.showLoading({
title: `下载中 ${res.progress}%`,
})
// 下载完成后隐藏loading
if (res.progress >= 100) {
setTimeout(() => {
wx.hideLoading()
}, 500)
}
})
},
// 显示权限提示弹窗
showPermissionModal(content = '请开启相册访问权限') {
wx.showModal({
title: '提示',
content: content,
confirmText: '去开启',
cancelText: '取消',
success: (res) => {
if (res.confirm) {
wx.openSetting({
withSubscriptions: true,
})
}
}
})
},