imageCache.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * 图片缓存
  3. */
  4. /*
  5. * @description 获取文件的缓存路径,如果文件未缓存,则直接返回网络路径,并下载缓存
  6. * @method getImageCache
  7. * @param {String} filePath 完整的图片下载路径,如果没有从缓存中获取到,则用这个路径去下载
  8. * @param {String} fileMd5 文件md5,必须唯一
  9. * @return {Object} promise对象
  10. */
  11. const getImageCache = (filePath, fileMd5) => {
  12. // 图片缓存key值
  13. let storageKey = 'IMAGE_CACHE_INFO_' + fileMd5
  14. // 首先获取本地存储的数据,查询是否有对应文件路径,如果有缓存内容,直接返回
  15. const cacheFileInfo = uni.getStorageSync(storageKey)
  16. if (cacheFileInfo) {
  17. // console.log("已缓存为:" + cacheFileInfo)
  18. return cacheFileInfo
  19. } else {
  20. // console.log("未缓存,进行下载保存")
  21. // 如果没有,执行下载,并存储起来后
  22. uni.downloadFile({
  23. url: filePath,
  24. success: (res) => {
  25. if (res.statusCode === 200) {
  26. // console.log('下载成功');
  27. // 再进行本地保存
  28. uni.saveFile({
  29. tempFilePath: res.tempFilePath,
  30. success: function(res2) {
  31. uni.setStorageSync(storageKey, res2.savedFilePath)
  32. return res2.savedFilePath
  33. },
  34. fail: function(res2) {
  35. return filePath
  36. }
  37. })
  38. } else {
  39. return filePath
  40. }
  41. },
  42. fail: (res) => {
  43. return filePath
  44. }
  45. })
  46. }
  47. }
  48. export default {
  49. getImageCache
  50. }