index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const downloadAndCache = (url, cacheKey) => {
  2. return new Promise((resolve, reject) => {
  3. wx.downloadFile({
  4. url,
  5. success(res) {
  6. if (res.statusCode === 200) {
  7. wx.setStorageSync(cacheKey, res.tempFilePath)
  8. resolve(res.tempFilePath)
  9. } else {
  10. reject(new Error('download failed:' + res.statusCode))
  11. }
  12. },
  13. fail: reject
  14. })
  15. })
  16. }
  17. export const clearImageCache = (caheKey => {
  18. if (cacheKey) {
  19. const cachedPath = wx.getStorageSync(cacheKey)
  20. if (cachedPath) {
  21. try {
  22. wx.removeSavedFile({ filePath: cachedPath })
  23. } catch (e) {
  24. console.warn('删除文件失败', e)
  25. }
  26. }
  27. wx.removeStorageSync(cacheKey)
  28. } else {
  29. // 清空所有图片缓存
  30. const info = wx.getStorageInfoSync()
  31. info.keys.forEach(key => {
  32. if (key.startsWith('image_cache_')) {
  33. const cachedPath = wx.getStorageSync(key)
  34. try {
  35. wx.removeSavedFile({ filePath: cachedPath })
  36. } catch (e) {
  37. console.warn('删除文件失败', e)
  38. }
  39. wx.removeStorageSync(key)
  40. }
  41. })
  42. }
  43. })
  44. export const getCachedImage = (url, cacheKey) => {
  45. return new Promise((res, rej) => {
  46. const cachedPath = wx.getStorageSync(cacheKey)
  47. if (cachedPath) {
  48. wx.getFileInfo({
  49. filePath: cachedPath,
  50. success() {
  51. res(cachedPath)
  52. },
  53. fail() {
  54. downloadAndCache(url, cacheKey).then(res).catch(rej)
  55. }
  56. })
  57. } else {
  58. downloadAndCache(url, cacheKey).then(res).catch(rej)
  59. }
  60. })
  61. }
  62. export const hash = (str) => {
  63. let hash = 0
  64. for (let i = 0; i < str.length; i++) {
  65. hash = ((hash << 5) - hash) + str.charCodeAt(i)
  66. hash |= 0
  67. }
  68. return hash.toString()
  69. }