uni-events-helper-wx
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 lines
3.2 KiB

3 years ago
  1. function pickExclude(obj, keys) {
  2. if (!uni.$u.test.object(obj)) {
  3. return {}
  4. }
  5. return Object.keys(obj).reduce((prev, key) => {
  6. if (!keys.includes(key)) {
  7. prev[key] = obj[key]
  8. }
  9. return prev
  10. }, {})
  11. }
  12. function formatImage(res) {
  13. return res.tempFiles.map((item) => ({
  14. ...pickExclude(item, ['path']),
  15. type: 'image',
  16. url: item.path,
  17. thumb: item.path
  18. }))
  19. }
  20. function formatVideo(res) {
  21. return [
  22. {
  23. ...pickExclude(res, ['tempFilePath', 'thumbTempFilePath', 'errMsg']),
  24. type: 'video',
  25. url: res.tempFilePath,
  26. thumb: res.thumbTempFilePath
  27. }
  28. ]
  29. }
  30. function formatMedia(res) {
  31. return res.tempFiles.map((item) => ({
  32. ...pickExclude(item, ['fileType', 'thumbTempFilePath', 'tempFilePath']),
  33. type: res.type,
  34. url: item.tempFilePath,
  35. thumb: res.type === 'video' ? item.thumbTempFilePath : item.tempFilePath
  36. }))
  37. }
  38. function formatFile(res) {
  39. return res.tempFiles.map((item) => ({ ...pickExclude(item, ['path']), url: item.path }))
  40. }
  41. export function chooseFile({
  42. accept,
  43. multiple,
  44. capture,
  45. compressed,
  46. maxDuration,
  47. sizeType,
  48. camera,
  49. maxCount
  50. }) {
  51. return new Promise((resolve, reject) => {
  52. switch (accept) {
  53. case 'image':
  54. uni.chooseImage({
  55. count: multiple ? Math.min(maxCount, 9) : 1,
  56. sourceType: capture,
  57. sizeType,
  58. success: (res) => resolve(formatImage(res)),
  59. fail: reject
  60. })
  61. break
  62. // #ifdef MP-WEIXIN
  63. // 只有微信小程序才支持chooseMedia接口
  64. case 'media':
  65. wx.chooseMedia({
  66. count: multiple ? Math.min(maxCount, 9) : 1,
  67. sourceType: capture,
  68. maxDuration,
  69. sizeType,
  70. camera,
  71. success: (res) => resolve(formatMedia(res)),
  72. fail: reject
  73. })
  74. break
  75. // #endif
  76. case 'video':
  77. uni.chooseVideo({
  78. sourceType: capture,
  79. compressed,
  80. maxDuration,
  81. camera,
  82. success: (res) => resolve(formatVideo(res)),
  83. fail: reject
  84. })
  85. break
  86. // #ifdef MP-WEIXIN || H5
  87. // 只有微信小程序才支持chooseMessageFile接口
  88. case 'file':
  89. // #ifdef MP-WEIXIN
  90. wx.chooseMessageFile({
  91. count: multiple ? maxCount : 1,
  92. type: accept,
  93. success: (res) => resolve(formatFile(res)),
  94. fail: reject
  95. })
  96. // #endif
  97. // #ifdef H5
  98. // 需要hx2.9.9以上才支持uni.chooseFile
  99. uni.chooseFile({
  100. count: multiple ? maxCount : 1,
  101. type: accept,
  102. success: (res) => resolve(formatFile(res)),
  103. fail: reject
  104. })
  105. // #endif
  106. break
  107. // #endif
  108. }
  109. })
  110. }