uni.downloadFile跟uni.saveFile区别
uni.downloadFile下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。当用户杀掉app进程时,uni.downloadFile下载文件资源路径就会失效
uni.downloadFile({
url: 'https://www.example.com/file/test', //仅为示例,并非真实的资源
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功');
}
}
});
uni.saveFile保存文件到本地。永久保存,除非用户手动删除,但是保存位置较为奇葩,为
“内部存储\Android\data\io.dcloud.HBuilder\apps\HBuilder\doc\uniapp_save”
uni.downloadFile({
url: 'http://img.netbian.com/file/2019/0414/7bee7eef5fc44417a0b02a46576e7e16.jpg', //仅为示例,并非真实的资源
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功');
}
uni.saveFile({
tempFilePath: res.tempFilePath,
success: function(red) {
console.log(red.savedFilePath)
}
});
}
});
开始编写代码
- 图片缓存加载
//选择点击图片进行放大
function selImg(url) {
let imgPath = localStorage.get('Recognize-' + url)
state.activeImg = imgPath
}
//判断图片是否加载过,已经加载过读取缓存,未加载过就原图片进行加载 并缓存,下次就可以读取缓存了
function imgLoad(index, src) {
let imgPath = localStorage.get('Recognize-' + src)
let storageKey = 'Recognize-' + src
if (imgPath) {
state.getAiVideoAlarmList[index].imageLoaded = true
} else {
uni.downloadFile({
url: src,
success: function(res) {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: function(res2) {
// console.log(res2)
localStorage.set(storageKey, res2.savedFilePath)
state.getAiVideoAlarmList[index].imageLoaded = true
}
})
}
}
})
}
}
//判断图片是否加载过,已经加载过读取缓存,未加载过就原图片进行加载
function imgSrc(src){
let imgPath = localStorage.get('Recognize-' + src)
if (imgPath) {
return imgPath
} else {
return src
}
}
- 计算缓存的图片一共多少mb大小
uni.getSavedFileList({
success: function(res) {
console.log(res.fileList);
const totalSizeBytes = res.fileList.reduce((total, file) => total + file.size, 0);
const totalSizeMB = totalSizeBytes / (1024 * 1024);
state.cacheSize = totalSizeMB.toFixed(2)
}
});
- 清除已经缓存的图片
confrimPopup.value.confrim('info', '確定清除緩存嗎(主要是AI識別的圖片緩存)', () => {
const keys = uni.getStorageInfoSync().keys;
let deleteCount = 0;
const recognizeKeys = keys.filter(key => key.startsWith('Recognize-'))
keys.forEach(key => {
if (key.startsWith('Recognize-')) {
uni.removeSavedFile({
filePath: localStorage.get(key),
complete: function(res) {
deleteCount++
// console.log(recognizeKeys.length,deleteCount, localStorage.get(key))
uni.removeStorageSync(key);
if (deleteCount == recognizeKeys.length) {
state.cacheSize = '0.00'
messagePopup.value.showMessage('success', '清除緩存成功');
}
}
});
}
});
}, () => {});