upload.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import type { UploadProps, UploadRawFile } from 'element-plus'
  2. import { getAccessToken } from '@/utils/auth'
  3. const message = useMessage() // 消息
  4. const HEADERS = { Authorization: 'Bearer ' + getAccessToken() } // 请求头
  5. // const UPLOAD_URL = 'http://127.0.0.1:8000/upload/' // 上传地址
  6. const UPLOAD_URL = import.meta.env.VITE_BASE_URL + '/admin-api/mp/material/upload-permanent' // 上传地址
  7. enum MaterialType {
  8. Image = 'image',
  9. Voice = 'voice',
  10. Video = 'video'
  11. }
  12. interface UploadData {
  13. type: MaterialType
  14. title: string
  15. introduction: string
  16. }
  17. const beforeUpload = (rawFile: UploadRawFile, materialType: MaterialType): boolean => {
  18. let allowTypes: string[] = []
  19. let maxSizeMB = 0
  20. let name = ''
  21. switch (materialType) {
  22. case MaterialType.Image:
  23. allowTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/jpg']
  24. maxSizeMB = 2
  25. name = '图片'
  26. break
  27. case MaterialType.Voice:
  28. allowTypes = ['audio/mp3', 'audio/mpeg', 'audio/wma', 'audio/wav', 'audio/amr']
  29. maxSizeMB = 2
  30. name = '图片'
  31. break
  32. case MaterialType.Video:
  33. allowTypes = ['video/mp4']
  34. maxSizeMB = 10
  35. name = '视频'
  36. break
  37. }
  38. // 格式不正确
  39. if (!allowTypes.includes(rawFile.type)) {
  40. message.error(`上传${name}格式不对!`)
  41. return false
  42. }
  43. // 大小不正确
  44. if (rawFile.size / 1024 / 1024 > maxSizeMB) {
  45. message.error(`上传${name}大小不能超过${maxSizeMB}M!`)
  46. return false
  47. }
  48. return true
  49. }
  50. const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) =>
  51. beforeUpload(rawFile, MaterialType.Image)
  52. const beforeVoiceUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) =>
  53. beforeUpload(rawFile, MaterialType.Voice)
  54. const beforeVideoUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) =>
  55. beforeUpload(rawFile, MaterialType.Video)
  56. export {
  57. HEADERS,
  58. UPLOAD_URL,
  59. MaterialType,
  60. UploadData,
  61. beforeImageUpload,
  62. beforeVoiceUpload,
  63. beforeVideoUpload
  64. }