utils.js 2.4 KB

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