index.vue 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. <template>
  2. <div class="app-upload">
  3. <el-upload ref="uploadRef" :headers="headers" :accept="acceptTypes.join(',')" v-model:file-list="fileList"
  4. :limit="limit" :multiple="limit > 1" :action="uploadUrl" :before-upload="onBeforeUpload"
  5. :on-success="onSuccess" :on-preview="onPreview" :on-exceed="onExceed" :on-change="onChange">
  6. <template #tip>
  7. <div class="el-upload__tip">
  8. <slot name="tip"></slot>
  9. </div>
  10. </template>
  11. <slot>
  12. <el-button type="primary">{{ t('operation.upload') }}</el-button>
  13. </slot>
  14. </el-upload>
  15. <el-image-viewer :url-list="imageList" :initial-index="imageIndex" @close="onViewerClose" v-if="showViewer"
  16. teleported />
  17. </div>
  18. </template>
  19. <script lang="ts" setup>
  20. import { shallowRef, shallowReactive, computed, PropType, onMounted } from 'vue'
  21. import { ElMessage, UploadProps, UploadRawFile, UploadUserFile, UploadFile, UploadFiles, UploadInstance, genFileId } from 'element-plus'
  22. import { i18n, useLoginStore } from '@/stores'
  23. import { localData } from '@/stores/storage'
  24. import service from '@/services'
  25. import cryptojs from 'crypto-js'
  26. const props = defineProps({
  27. modelValue: {
  28. type: Array as PropType<UploadUserFile[]>,
  29. default: () => ([])
  30. },
  31. fileTypes: {
  32. type: Array as PropType<readonly ('image' | 'pdf' | 'word' | 'excel')[]>,
  33. default: () => ([])
  34. },
  35. limit: {
  36. type: Number,
  37. default: 1
  38. },
  39. maxSize: {
  40. type: Number,
  41. default: 0
  42. },
  43. typeMessage: {
  44. type: String,
  45. default: '请选择正确的文件类型'
  46. }
  47. })
  48. const { global: { t } } = i18n
  49. const emit = defineEmits(['update:modelValue', 'change'])
  50. const fileList = computed({
  51. get: () => props.modelValue,
  52. set: (val) => emit('update:modelValue', val)
  53. })
  54. const uploadUrl = service.getConfig('apiUrl') + '/common/uploadFile'
  55. const uploadRef = shallowRef<UploadInstance>()
  56. const showViewer = shallowRef(false)
  57. const acceptTypes = shallowReactive<string[]>([]) // 接受上传的文件类型
  58. const uploadTypes = shallowReactive<string[]>([]) // 允许上传的文件类型
  59. const imageIndex = shallowRef(0)
  60. const imageTypes = ['image/png', 'image/jpeg']
  61. const loginStore = useLoginStore()
  62. const timestamp = new Date().getTime()
  63. const headers = {
  64. 'Accept-Language': localData.getValue('appLanguage'),
  65. 'Sign-Id': loginStore.signId,
  66. Sign: cryptojs.SHA256(loginStore.sign + timestamp.toString()).toString(),
  67. Authorization: loginStore.token,
  68. Timestamp: timestamp.toString(),
  69. }
  70. // 预览图列表
  71. const imageList = computed(() => {
  72. return fileList.value.reduce<string[]>((pre, { url, raw }) => {
  73. // 判断是否图片类型
  74. if (url && raw && imageTypes.includes(raw.type)) {
  75. pre.push(url)
  76. }
  77. return pre
  78. }, [])
  79. })
  80. const onSuccess = (response: { code: number }, uploadFile: UploadFile) => {
  81. const { url, raw } = uploadFile
  82. if (response.code === 200) {
  83. if (!url && raw) {
  84. uploadFile.url = URL.createObjectURL(raw)
  85. }
  86. } else {
  87. fileList.value.pop()
  88. }
  89. }
  90. const onChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  91. emit('change', uploadFile, uploadFiles)
  92. }
  93. // 当超出限制时的回调
  94. const onExceed = (files: File[]) => {
  95. if (props.limit === 1) {
  96. const el = uploadRef.value
  97. if (el) {
  98. const rawFile = files[0] as UploadRawFile
  99. if (!uploadTypes.length || uploadTypes.includes(rawFile.type)) {
  100. rawFile.uid = genFileId()
  101. el.clearFiles()
  102. el.handleStart(rawFile)
  103. el.submit()
  104. } else {
  105. ElMessage.warning(props.typeMessage)
  106. }
  107. }
  108. } else {
  109. ElMessage.warning(`最多只能上传${props.limit}个文件`)
  110. }
  111. }
  112. // 上传之前判断文件类型
  113. const onBeforeUpload = (rawFile: UploadRawFile) => {
  114. if (!uploadTypes.length || uploadTypes.includes(rawFile.type)) {
  115. return true
  116. }
  117. ElMessage.warning(props.typeMessage)
  118. return false
  119. }
  120. // 打开预览图
  121. const onPreview: UploadProps['onPreview'] = ({ url }: UploadFile) => {
  122. const index = imageList.value.findIndex((val) => val === url)
  123. if (index > -1) {
  124. imageIndex.value = index
  125. showViewer.value = true
  126. } else {
  127. window.open(url, '_blank')
  128. }
  129. }
  130. const onViewerClose = () => {
  131. showViewer.value = false
  132. }
  133. onMounted(() => {
  134. props.fileTypes.forEach((value) => {
  135. switch (value) {
  136. case 'image': {
  137. acceptTypes.push('.jpg', '.jpeg', '.png')
  138. uploadTypes.push(...imageTypes)
  139. break
  140. }
  141. case 'pdf': {
  142. acceptTypes.push('.pdf')
  143. uploadTypes.push('application/pdf')
  144. break
  145. }
  146. case 'word': {
  147. acceptTypes.push('.doc', '.docx')
  148. uploadTypes.push('application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  149. break
  150. }
  151. case 'excel': {
  152. acceptTypes.push('.xls', '.xlsx')
  153. uploadTypes.push('application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  154. break
  155. }
  156. }
  157. })
  158. })
  159. </script>
  160. <style lang="less">
  161. @import './index.less';
  162. </style>