UploadFile.vue 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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="(isUploading = true)"
  10. :on-error="onUploadError"
  11. :before-upload="onBeforeUpload"
  12. :on-success="onUploadSuccess"
  13. >
  14. <el-button type="primary" plain :loading="isUploading" :disabled="isUploading">
  15. {{ isUploading ? '正在上传' : '点击上传' }}
  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 isUploading = ref(false)
  46. /** 上传前检查 */
  47. const onBeforeUpload = props.type === MaterialType.Image ? beforeImageUpload : beforeVoiceUpload
  48. /** 上传成功处理 */
  49. const onUploadSuccess: UploadProps['onSuccess'] = (res: any) => {
  50. if (res.code !== 0) {
  51. message.alertError('上传出错:' + res.msg)
  52. return false
  53. }
  54. // 清空上传时的各种数据
  55. fileList.value = []
  56. uploadData.title = ''
  57. uploadData.introduction = ''
  58. message.notifySuccess('上传成功')
  59. isUploading.value = false
  60. emit('uploaded')
  61. }
  62. /** 上传失败处理 */
  63. const onUploadError = (err: Error) => message.error('上传失败: ' + err.message)
  64. </script>
  65. <style lang="scss" scoped>
  66. .el-upload__tip {
  67. margin-left: 5px;
  68. }
  69. </style>