utils.js 2.3 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}个文件 ,${res.tempFiles.length - files.length} 个文件格式不正确`,
  49. icon: 'none',
  50. duration: 5000
  51. })
  52. }
  53. return {
  54. filePaths,
  55. files
  56. }
  57. }
  58. /**
  59. * 获取图片信息
  60. * @param {Object} filepath
  61. */
  62. export const get_file_info = (filepath) => {
  63. return new Promise((resolve, reject) => {
  64. uni.getImageInfo({
  65. src: filepath,
  66. success(res) {
  67. resolve(res)
  68. },
  69. fail(err) {
  70. reject(err)
  71. }
  72. })
  73. })
  74. }
  75. /**
  76. * 获取封装数据
  77. */
  78. export const get_file_data = async (files, type = 'image') => {
  79. // 最终需要上传数据库的数据
  80. let fileFullName = get_file_ext(files.name)
  81. const extname = fileFullName.ext.toLowerCase()
  82. let filedata = {
  83. name: files.name,
  84. uuid: files.uuid,
  85. extname: extname || '',
  86. cloudPath: files.cloudPath,
  87. fileType: files.fileType,
  88. thumbTempFilePath: files.thumbTempFilePath,
  89. url: files.path || 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. }