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

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

用到的相关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.

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

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

相关推荐
2501_915921435 小时前
iOS App 电耗管理 通过系统电池记录、Xcode Instruments 与克魔(KeyMob)组合使用
android·ios·小程序·https·uni-app·iphone·webview
難釋懷5 小时前
SpringDataRedis数据序列化器
redis·缓存
数字游民95277 小时前
2小时VibeCoding了一个看图猜词小程序:猜对了么
人工智能·ai·小程序·ai绘画·数字游民9527
qq_124987075312 小时前
基于小程序中医食谱推荐系统的设计(源码+论文+部署+安装)
java·spring boot·后端·微信小程序·小程序·毕业设计·计算机毕业设计
RoboWizard14 小时前
8TB SSD还有掉速问题吗?
人工智能·缓存·智能手机·电脑·金士顿
2501_9159184115 小时前
iOS App 测试方法,Xcode、TestFlight与克魔(KeyMob)等工具组合使用
android·macos·ios·小程序·uni-app·iphone·xcode
棒棒的唐16 小时前
微信小程序右上角分享按钮如何根据用户登录状态确定是否允许分享
微信小程序·小程序
2501_9159214316 小时前
iOS 描述文件制作过程,从 Bundle ID、证书、设备到描述文件生成后的验证
android·ios·小程序·https·uni-app·iphone·webview
小白学大数据16 小时前
基于 Python 的知网文献批量采集与可视化分析
开发语言·爬虫·python·小程序
毕设源码-郭学长16 小时前
【开题答辩全过程】以 基于微信小程序的医院管理系统为例,包含答辩的问题和答案
微信小程序·小程序