upload.ts 1.9 KB

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