UploadFile.vue 1.6 KB

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