UploadFile.vue 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <template>
  2. <el-upload
  3. :action="UPLOAD_URL"
  4. :headers="HEADERS"
  5. multiple
  6. :limit="1"
  7. :file-list="fileList"
  8. :data="uploadData"
  9. :on-progress="() => (uploading = true)"
  10. :on-error="(err: Error) => message.error(`上传失败: ${err.message}`)"
  11. :before-upload="beforeUpload"
  12. :on-success="handleUploadSuccess"
  13. >
  14. <el-button type="primary" plain :loading="uploading" :disabled="uploading">
  15. {{ uploading ? '正在上传' : '点击上传' }}
  16. </el-button>
  17. <template #tip>
  18. <span class="el-upload__tip" style="margin-left: 5px">
  19. <slot></slot>
  20. </span>
  21. </template>
  22. </el-upload>
  23. </template>
  24. <script setup lang="ts">
  25. import type { UploadProps, UploadUserFile } from 'element-plus'
  26. import {
  27. HEADERS,
  28. UPLOAD_URL,
  29. UploadData,
  30. MaterialType,
  31. beforeImageUpload,
  32. beforeVoiceUpload
  33. } from './upload'
  34. const message = useMessage()
  35. const props = defineProps<{ type: MaterialType }>()
  36. const fileList = ref<UploadUserFile[]>([])
  37. const emit = defineEmits<{
  38. (e: 'uploaded', v: void)
  39. }>()
  40. const uploadData: UploadData = reactive({
  41. type: MaterialType.Image,
  42. title: '',
  43. introduction: ''
  44. })
  45. const uploading = ref(false)
  46. const beforeUpload = props.type === MaterialType.Image ? beforeImageUpload : beforeVoiceUpload
  47. const handleUploadSuccess: UploadProps['onSuccess'] = (res: any) => {
  48. if (res.code !== 0) {
  49. message.alertError('上传出错:' + res.msg)
  50. return false
  51. }
  52. // 清空上传时的各种数据
  53. fileList.value = []
  54. uploadData.title = ''
  55. uploadData.introduction = ''
  56. message.notifySuccess('上传成功')
  57. uploading.value = false
  58. emit('uploaded')
  59. }
  60. </script>