const downloadAndCache = (url, cacheKey) => { return new Promise((resolve, reject) => { wx.downloadFile({ url, success(res) { if (res.statusCode === 200) { wx.setStorageSync(cacheKey, res.tempFilePath) resolve(res.tempFilePath) } else { reject(new Error('download failed:' + res.statusCode)) } }, fail: reject }) }) } export const clearImageCache = (caheKey => { if (cacheKey) { const cachedPath = wx.getStorageSync(cacheKey) if (cachedPath) { try { wx.removeSavedFile({ filePath: cachedPath }) } catch (e) { console.warn('删除文件失败', e) } } wx.removeStorageSync(cacheKey) } else { // 清空所有图片缓存 const info = wx.getStorageInfoSync() info.keys.forEach(key => { if (key.startsWith('image_cache_')) { const cachedPath = wx.getStorageSync(key) try { wx.removeSavedFile({ filePath: cachedPath }) } catch (e) { console.warn('删除文件失败', e) } wx.removeStorageSync(key) } }) } }) export const getCachedImage = (url, cacheKey) => { return new Promise((res, rej) => { const cachedPath = wx.getStorageSync(cacheKey) if (cachedPath) { wx.getFileInfo({ filePath: cachedPath, success() { res(cachedPath) }, fail() { downloadAndCache(url, cacheKey).then(res).catch(rej) } }) } else { downloadAndCache(url, cacheKey).then(res).catch(rej) } }) } export const hash = (str) => { let hash = 0 for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash) + str.charCodeAt(i) hash |= 0 } return hash.toString() }