数据缓存以及文件缓存
更新时间: 2025-10-14 13:55:19
# 前言
在移动应用开发中,缓存机制是提升用户体验和减少网络请求的关键技术。
UniApp作为跨平台框架,提供了丰富的本地存储API,其中uni.setStorageSync、uni.getStorageSync、uni.downloadFile和uni.saveFile是实现缓存策略的核心工具。
# 核心API功能解析
# 键值对存储setStorageSync与getStorageSync
uni.setStorageSync和uni.getStorageSync是UniApp提供的同步本地存储API,适用于保存配置信息、用户状态等小型数据。
基本用法:
// 存储数据(支持对象直接存储,无需手动JSON.stringify)
try {
uni.setStorageSync('user_config', {
theme: 'dark',
fontSize: 16,
lastLogin: new Date().toISOString()
});
} catch (e) {
console.error('存储失败:', e);
}
// 读取数据(自动解析为原数据类型)
const config = uni.getStorageSync('user_config') || { theme: 'light', fontSize: 14 };
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
关键特性:
- 跨平台差异:H5端对应localStorage(5MB限制),小程序端总上限10MB,App端无明确限制但建议控制在50MB内
- 数据类型:支持原生类型、Date及可序列化对象,无需手动转换
- 命名规范:避免使用uni-、dcloud-等系统保留前缀
# 文件下载与持久化downloadFile与saveFile
对于图片、PDF等二进制资源,需结合uni.downloadFile和uni.saveFile实现缓存。
完整流程:
/**
* 下载并缓存文件
* @param {string} url - 资源URL
* @param {string} key - 缓存键名
* @returns {Promise<string>} 本地文件路径
*/
async function downloadAndCacheFile(url, key) {
// 1. 检查本地缓存
const cachedPath = uni.getStorageSync(key);
if (cachedPath) {
// 验证文件是否存在(可选)
const fs = uni.getFileSystemManager();
try {
await fs.access({ filePath: cachedPath });
return cachedPath; // 文件存在,直接返回
} catch (e) {
console.log('缓存文件已删除,重新下载');
}
}
// 2. 下载文件到临时路径
const downloadRes = await uni.downloadFile({ url });
if (downloadRes.statusCode !== 200) {
throw new Error(`下载失败: ${downloadRes.statusCode}`);
}
// 3. 保存到永久路径
const saveRes = await uni.saveFile({ tempFilePath: downloadRes.tempFilePath });
// 4. 记录缓存信息(含过期时间)
uni.setStorageSync(key, {
path: saveRes.savedFilePath,
expire: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天有效期
});
return saveRes.savedFilePath;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
注意事项:
- uni.downloadFile返回临时路径(tempFilePath),应用重启后可能失效
- uni.saveFile将文件移动到持久化目录,返回savedFilePath需通过Storage记录
- H5端受浏览器限制,建议使用a标签触发下载而非缓存
其实app缓存还可以考虑用App端的SQLite