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

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

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

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

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

相关推荐
zlp19929 分钟前
软考(系统架构师)-案例分析之Redis与缓存
redis·缓存·软考高级·软考·系统架构师
苏灵凯33 分钟前
智能环境监测终端全栈设计:从单片机到微信小程序,手把手搞定!
单片机·嵌入式硬件·mcu·物联网·微信小程序·小程序·蓝牙模块
nhc0881 小时前
贵阳纳海川科技有限公司・货运物流行业解决方案
科技·微信小程序·小程序·软件开发·小程序开发
小雨青年1 小时前
当缓存成为生产力:GitHub Actions 缓存机制的深度优化指南
缓存·github
admin and root1 小时前
AWS S3 对象存储攻防&云安全之OSS存储桶漏洞
微信小程序·小程序·渗透测试·云计算·aws·src·攻防演练
山檐雾1 小时前
C#泛型缓存
缓存·c#
取码网1 小时前
新版点微同城主题源码34.7+全套插件+小程序前后端 源文件
小程序
2501_915918411 小时前
iOS 混淆流程 提升 IPA 分析难度 实现 IPA 深度加固
android·ios·小程序·https·uni-app·iphone·webview
星夜泊客3 小时前
《Lua 模块化核心:require 的地址传递与缓存机制》
缓存·lua
布吉岛没有岛_3 小时前
小程序接入智能体
小程序·智能体