uniapp开发微信小程序实现图片本地缓存(策略)

开发微信小程序时,小程序中使用的图片较多时,图片CDN流量就会增加,进而带来支出流量费用增加,图片加载变慢,影响用户体验等问题。为此,我们可以利用小程序的图片本地缓存机制来解决以上问题

实现思路

在图片首次加载的时候,先下载图片

下载完成之后就会返回图片在本地存储的地址,然后在小程序缓存中存储本地图片路径,这里的关键点是:小程序缓存的形式是:( 键:值 ),其中是图片的CDN路径,为图片本地图片路径。

那么,在之后拿到请求数据的时候,我们拿到的是图片的CDN路径,这里我们就得到了一个键,然后我们拿到这个键的键值。这个键值就是图片的本地存储路径。

这个时候,我们不能马上就将CDN路径替换掉本地存储路径,因为,我们不确定这个存储路径是否有效,还需要获取到图片文件列表,检查文件列表中是否有该路径,如果有,证明路径有效,就将本地存储路径替换为CDN图片路径。

这样我们就达到了实现图片本地缓存的效果

图片缓存函数,函数返回缓存路径

//图片缓存
async saveImage(image) {
	let th = this;
	try {
		// 下载文件
		let fs = uni.getFileSystemManager();
		const {
			tempFilePath
		} = await new Promise((resolve, reject) => {
			uni.downloadFile({
				url: image,
				success: (res) => {
					if (res.statusCode === 200) {
						resolve(res);
					} else {
						reject(new Error('下载失败,状态码非200'));
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
		// 将下载的图片保存到本地(可选,如果只是想缓存路径则不需要这一步)  
		const savedFilePath = await new Promise((resolve, reject) => {
			const fs = uni.getFileSystemManager();
			fs.saveFile({
				tempFilePath: tempFilePath,
				success: (saveres) => {
					//更新数组
					let ch = {
						filePath: saveres.savedFilePath,
						size: 1000,
						createTime: 1000
					}
					th.globalData.FileList.push(ch)
					resolve(saveres.savedFilePath);
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
		// 缓存图片URL到本地存储,映射到其保存路径(如果不需要保存文件到本地,则跳过上一步并直接存储URL)
		const strImage = image.toString();
		uni.setStorageSync(strImage, savedFilePath);
		// 返回缓存路径(如果需要的话)  
		return savedFilePath;
	} catch (error) {
		console.error('保存图片过程中发生错误', error);
		throw error; // 可以选择重新抛出错误,以便在调用者中处理  
	}
},

检查图片缓存路径是否有效

//查看图片是否有缓存
async issave(imageKey) {
	let th = this;
	return new Promise((resolve, reject) => {
		let simage = uni.getStorageSync(imageKey);
		const fs = uni.getFileSystemManager();
		if (simage !== "") {
			let imagelist = this.globalData.FileList;
			if (imagelist.length <= 0) {
				fs.getSavedFileList({
					success: function(res) {
						let imagelist = res.fileList;
						th.globalData.FileList = imagelist;
						let foundImage = imagelist.find(image => image.filePath ===
							simage);
						if (foundImage) {
							resolve(foundImage.filePath);
						} else {
							resolve(false); // 如果没有找到匹配的图片,返回false
						}
					},
					fail: function(err) {
						reject(err); // 获取文件列表失败时,通过reject返回错误  
					}
				});
			} else {
				let foundImage = imagelist.find(image => image.filePath ===
					simage);
				if (foundImage) {
					resolve(foundImage.filePath);
				} else {
					resolve(false); // 如果没有找到匹配的图片,返回false
				}
			}
		} else {
			resolve(false); // 如果没有保存的图片标识符,直接返回false  
		}
	});
},

函数中实现的只是思想,其中细节还需开发者自己探讨

以上就是实现图片本地缓存的策略,如果有其他想法,欢迎在评论区留言!!!

你可能感兴趣的:(uni-app,微信小程序,缓存)