index.js 2.2 KB

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