UploadFile.vue 1.5 KB

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