UploadFile.vue 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 lang="ts" setup>
  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 accountId = inject<number>('accountId')
  34. const fileList = ref<UploadUserFile[]>([])
  35. const emit = defineEmits<{
  36. (e: 'uploaded', v: void)
  37. }>()
  38. const uploadData: UploadData = reactive({
  39. type: UploadType.Image,
  40. title: '',
  41. introduction: '',
  42. accountId: accountId!
  43. })
  44. /** 上传前检查 */
  45. const onBeforeUpload = props.type === UploadType.Image ? beforeImageUpload : beforeVoiceUpload
  46. /** 上传成功处理 */
  47. const onUploadSuccess: 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. emit('uploaded')
  58. }
  59. /** 上传失败处理 */
  60. const onUploadError = (err: Error) => message.error('上传失败: ' + err.message)
  61. </script>
  62. <style lang="scss" scoped>
  63. .el-upload__tip {
  64. margin-left: 5px;
  65. }
  66. </style>