小程序网络大文件缓存方案

分享一个小程序网络大图加载慢的解决方案

用到的相关api

  1. getSavedFileList 获取已保存的文件列表;
  2. getStorageSync 获取本地缓存;
  3. downloadFile 下载网络图片;
  4. saveFile 保存文件到本地;
  5. setStorage 将数据储存到小程序本地缓存;

整体思路如下:

先获取已保存的本地文件,如果从来没有保存过,就先下载网络图片并保存到本地,同时将文件路劲缓存到小程序,等下次需要的时候直接拿文件路径去匹配本地文件的路径,实现图片秒开的效果;

遗留问题:需要先加载再缓存,初次加载还是会加载比较慢?

代码实现

javascript 复制代码
uni.getSavedFileList({
	complete: (res)=> {
		console.log(res)

		const cacheImgKey = uni.getStorageSync('cacheImgKey')
		if(res.fileList.length) {
			const data = res.fileList.find(item=> item.filePath == cacheImgKey)
			if(data) {
				this.imagePath = data.filePath
				return
			}
		}

		// 首次加载等待
		uni.showLoading({
			title: '加载中...'
		})
		uni.downloadFile({
			url: '要加载的网络文件地址',
			success: ({ tempFilePath })=> {
				this.imagePath = tempFilePath
				uni.saveFile({
					tempFilePath,
					success: ({ savedFilePath })=> {
						this.imagePath = savedFilePath
					},
					complete: ()=> {
						uni.hideLoading()
						uni.setStorage({
							key: 'cacheImgKey',
							data: this.imagePath
						})
					}
				})
			}
		})
	}
})

解决遗留的问题,即 初次加载也能达到秒开的效果,如何处理?

解决方案:可在前置页面预先加载并缓存文件

前置页面判断本地缓存,如果没有可先下载文件保存

javascript 复制代码
const cacheImgKey = uni.getStorageSync('cacheImgKey')
if(!cacheImgKey) {
	uni.downloadFile({
		url: '要加载的网络文件地址',
		success: ({ tempFilePath })=> {
			uni.saveFile({
				tempFilePath,
				success: ({ savedFilePath })=> {
					uni.setStorage({
						key: 'cacheImgKey',
						data: savedFilePath
					})
				}
			})
		}
	})
}

END.

如果觉得有用随手点个赞吧,谢谢

关注我,不定时分享技术干货~

相关推荐
要开心吖ZSH1 小时前
本地缓存方案选择指南:volatile、ConcurrentHashMap、Caffeine 怎么选?
缓存·caffeine·volatile·本地缓存
范什么特西1 小时前
redis题目面渣重点
数据库·redis·缓存
今天的砖头有点烫手啊1 小时前
接口太慢?Spring Boot 缓存体系 @Cacheable 全链路拆解
spring boot·后端·缓存
szephyr2 小时前
腾讯云 ADP 智能体的 Skills 版本回滚总是回到旧配置,是缓存没清还是版本管理没开?
java·缓存·腾讯云
凡科网小帆5 小时前
2026小程序商城做的比较好的品牌,怎么选小程序商城品牌
小程序·小程序商城
2501_915909066 小时前
iOS 证书创建与管理 类型限制 p12 密码与云备份实操
android·ios·小程序·https·uni-app·iphone·webview
油丶酸萝卜别吃6 小时前
Redis 布隆过滤器快速实现
数据库·redis·缓存
MC皮蛋侠客7 小时前
TDengine C++ 系列(8):流式计算与最新值缓存——库内实时处理
c++·缓存·tdengine
黄华SJ520it1 天前
顶俏洗衣液模式制度开发介绍:S2B2C社交分销+多门店核销系统全解析
前端·数据库·小程序·零售·系统开发
MC皮蛋侠客1 天前
Redis 系列(八):缓存设计模式与一致性——从 Cache Aside 到防雪崩
redis·缓存·设计模式