utils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * 获取文件名和后缀
  3. * @param {String} name
  4. */
  5. export const get_file_ext = (name) => {
  6. const last_len = name.lastIndexOf('.');
  7. const len = name.length;
  8. return {
  9. name: name.substring(0, last_len),
  10. ext: name.substring(last_len + 1, len),
  11. };
  12. };
  13. /**
  14. * 获取扩展名
  15. * @param {Array} fileExtname
  16. */
  17. export const get_extname = (fileExtname) => {
  18. if (!Array.isArray(fileExtname)) {
  19. let extname = fileExtname.replace(/(\[|\])/g, '');
  20. return extname.split(',');
  21. } else {
  22. return fileExtname;
  23. }
  24. return [];
  25. };
  26. /**
  27. * 获取文件和检测是否可选
  28. */
  29. export const get_files_and_is_max = (res, _extname) => {
  30. let filePaths = [];
  31. let files = [];
  32. if (!_extname || _extname.length === 0) {
  33. return {
  34. filePaths,
  35. files,
  36. };
  37. }
  38. res.tempFiles.forEach((v) => {
  39. let fileFullName = get_file_ext(v.name);
  40. const extname = fileFullName.ext.toLowerCase();
  41. if (_extname.indexOf(extname) !== -1) {
  42. files.push(v);
  43. filePaths.push(v.path);
  44. }
  45. });
  46. if (files.length !== res.tempFiles.length) {
  47. uni.showToast({
  48. title: `当前选择了${res.tempFiles.length}个文件 ,${
  49. res.tempFiles.length - files.length
  50. } 个文件格式不正确`,
  51. icon: 'none',
  52. duration: 5000,
  53. });
  54. }
  55. return {
  56. filePaths,
  57. files,
  58. };
  59. };
  60. /**
  61. * 获取图片信息
  62. * @param {Object} filepath
  63. */
  64. export const get_file_info = (filepath) => {
  65. return new Promise((resolve, reject) => {
  66. uni.getImageInfo({
  67. src: filepath,
  68. success(res) {
  69. resolve(res);
  70. },
  71. fail(err) {
  72. reject(err);
  73. },
  74. });
  75. });
  76. };
  77. /**
  78. * 获取封装数据
  79. */
  80. export const get_file_data = async (files, type = 'image') => {
  81. // 最终需要上传数据库的数据
  82. let fileFullName = get_file_ext(files.name);
  83. const extname = fileFullName.ext.toLowerCase();
  84. let filedata = {
  85. name: files.name,
  86. uuid: files.uuid,
  87. extname: extname || '',
  88. cloudPath: files.cloudPath,
  89. fileType: files.fileType,
  90. url: files.path || files.path,
  91. size: files.size, //单位是字节
  92. image: {},
  93. path: files.path,
  94. video: {},
  95. };
  96. if (type === 'image') {
  97. const imageinfo = await get_file_info(files.path);
  98. delete filedata.video;
  99. filedata.image.width = imageinfo.width;
  100. filedata.image.height = imageinfo.height;
  101. filedata.image.location = imageinfo.path;
  102. } else {
  103. delete filedata.image;
  104. }
  105. return filedata;
  106. };