file.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { CDN_CACHE_KEY } from '@/settings/enums';
  2. import { DEFAULT_CDN_URL, UPLOAD } from '@/settings/siteSetting';
  3. import { isString } from './is.js';
  4. /** 获取文件CDN前缀 */
  5. export async function getCdnUrl() {
  6. try {
  7. const res = 'xxxxxxxxxxx';
  8. uni.setStorageSync('CDN_UPLOAD', res.data + '/');
  9. } catch (error) {
  10. console.log(error);
  11. }
  12. }
  13. /**
  14. * 输出完整文件地址
  15. * @param url
  16. */
  17. export function getFileUrl(url, planB = false) {
  18. if (url === '') return url;
  19. if (!isString(url)) return url;
  20. // 特殊处理,/static 开头 是本地文件
  21. if (url.indexOf('/static') === 0) return url;
  22. if (/^(https|http):\/\//i.test(url) || /^(data|http|https):/i.test(url) || url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0) return url;
  23. // 如果第一位非 / 开头 补全指定目录前缀;接口返回的 upload/ 路径不再加 orderFood,直接拼 CDN
  24. if (!/^\//.test(url) && !planB && !/^upload\/?/i.test(String(url).trim())) url = `orderFood/${url}`;
  25. url = url.replace(/\.+\//gi, '/').replace(/~+/gi, '/').replace(/\/+/gi, '/').replace(/^\/+/, '').replace(/\\/g, '/');
  26. // CDN 路径 增加回退逻辑,防止当异步数据没有返回时,页面已经开始加载数据,导致图片无法正常显示
  27. let prefix = uni.getStorageSync(CDN_CACHE_KEY) || DEFAULT_CDN_URL;
  28. if (planB) prefix = uni.getStorageSync('CDN_UPLOAD') || UPLOAD;
  29. // ios老版本不支持webp(使用 getDeviceInfo 替代已废弃的 getSystemInfoSync)
  30. let platform = '';
  31. let systemVersion = '';
  32. try {
  33. if (typeof uni.getDeviceInfo === 'function') {
  34. const deviceInfo = uni.getDeviceInfo();
  35. platform = deviceInfo.platform || '';
  36. systemVersion = deviceInfo.system || '';
  37. } else {
  38. const systemInfo = uni.getSystemInfoSync();
  39. platform = systemInfo.platform || '';
  40. systemVersion = systemInfo.osVersion || systemInfo.system || '';
  41. }
  42. } catch (e) {}
  43. if (url.split('.')[1] == 'webp' && platform == 'ios') {
  44. const parts = systemVersion.split('.');
  45. const major = parts[0] || '0';
  46. const minor = parts[1] || '0';
  47. if (major < '18' || (major == '18' && minor < '2')) {
  48. url = url.split('.')[0] + '.jpg';
  49. }
  50. }
  51. return prefix + url;
  52. }