UploadFile.vue 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. ref="uploadRef"
  5. :multiple="props.limit > 1"
  6. name="file"
  7. v-model="valueRef"
  8. v-model:file-list="fileList"
  9. :show-file-list="true"
  10. :auto-upload="autoUpload"
  11. :action="updateUrl"
  12. :headers="uploadHeaders"
  13. :limit="props.limit"
  14. :drag="drag"
  15. :before-upload="beforeUpload"
  16. :on-exceed="handleExceed"
  17. :on-success="handleFileSuccess"
  18. :on-error="excelUploadError"
  19. :on-remove="handleRemove"
  20. :on-preview="handlePreview"
  21. class="upload-file-uploader"
  22. >
  23. <el-button type="primary"><Icon icon="ep:upload-filled" />选取文件</el-button>
  24. <template v-if="isShowTip" #tip>
  25. <div style="font-size: 8px">
  26. 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
  27. </div>
  28. <div style="font-size: 8px">
  29. 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b> 的文件
  30. </div>
  31. </template>
  32. </el-upload>
  33. </div>
  34. </template>
  35. <script setup lang="ts">
  36. import { ref, watch } from 'vue'
  37. import { useMessage } from '@/hooks/web/useMessage'
  38. import { propTypes } from '@/utils/propTypes'
  39. import { getAccessToken, getTenantId } from '@/utils/auth'
  40. import { ElUpload, UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
  41. const message = useMessage() // 消息弹窗
  42. const emit = defineEmits(['update:modelValue'])
  43. const props = defineProps({
  44. modelValue: propTypes.oneOfType([String, Object, Array]),
  45. title: propTypes.string.def('文件上传'),
  46. updateUrl: propTypes.string.def(import.meta.env.VITE_UPLOAD_URL),
  47. fileType: propTypes.array.def(['doc', 'xls', 'ppt', 'txt', 'pdf']), // 文件类型, 例如['png', 'jpg', 'jpeg']
  48. fileSize: propTypes.number.def(5), // 大小限制(MB)
  49. limit: propTypes.number.def(5), // 数量限制
  50. autoUpload: propTypes.bool.def(true), // 自动上传
  51. drag: propTypes.bool.def(false), // 拖拽上传
  52. isShowTip: propTypes.bool.def(true) // 是否显示提示
  53. })
  54. // ========== 上传相关 ==========
  55. const valueRef = ref(props.modelValue)
  56. const uploadRef = ref<UploadInstance>()
  57. const uploadList = ref<UploadUserFile[]>([])
  58. const fileList = ref<UploadUserFile[]>([])
  59. const uploadNumber = ref<number>(0)
  60. const uploadHeaders = ref({
  61. Authorization: 'Bearer ' + getAccessToken(),
  62. 'tenant-id': getTenantId()
  63. })
  64. watch(
  65. () => props.modelValue,
  66. (val) => {
  67. if (val) {
  68. // 首先将值转为数组, 当只穿了一个图片时,会报map方法错误
  69. const list = Array.isArray(props.modelValue)
  70. ? props.modelValue
  71. : Array.isArray(props.modelValue?.split(','))
  72. ? props.modelValue?.split(',')
  73. : Array.of(props.modelValue)
  74. // 然后将数组转为对象数组
  75. fileList.value = list.map((item) => {
  76. if (typeof item === 'string') {
  77. // edit by 芋道源码
  78. item = { name: item, url: item }
  79. }
  80. return item
  81. })
  82. } else {
  83. fileList.value = []
  84. return []
  85. }
  86. },
  87. {
  88. deep: true,
  89. immediate: true
  90. }
  91. )
  92. // 文件上传之前判断
  93. const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
  94. if (fileList.value.length >= props.limit) {
  95. message.error(`上传文件数量不能超过${props.limit}个!`)
  96. return false
  97. }
  98. let fileExtension = ''
  99. if (file.name.lastIndexOf('.') > -1) {
  100. fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  101. }
  102. const isImg = props.fileType.some((type: string) => {
  103. if (file.type.indexOf(type) > -1) return true
  104. return !!(fileExtension && fileExtension.indexOf(type) > -1)
  105. })
  106. const isLimit = file.size < props.fileSize * 1024 * 1024
  107. if (!isImg) {
  108. message.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`)
  109. return false
  110. }
  111. if (!isLimit) {
  112. message.error(`上传文件大小不能超过${props.fileSize}MB!`)
  113. return false
  114. }
  115. message.success('正在上传文件,请稍候...')
  116. uploadNumber.value++
  117. }
  118. // 处理上传的文件发生变化
  119. // const handleFileChange = (uploadFile: UploadFile): void => {
  120. // uploadRef.value.data.path = uploadFile.name
  121. // }
  122. // 文件上传成功
  123. const handleFileSuccess: UploadProps['onSuccess'] = (res: any): void => {
  124. message.success('上传成功')
  125. uploadList.value.push({ name: res.data, url: res.data })
  126. if (uploadList.value.length == uploadNumber.value) {
  127. fileList.value = fileList.value.concat(uploadList.value)
  128. uploadList.value = []
  129. uploadNumber.value = 0
  130. emit('update:modelValue', listToString(fileList.value))
  131. }
  132. }
  133. // 文件数超出提示
  134. const handleExceed: UploadProps['onExceed'] = (): void => {
  135. message.error(`上传文件数量不能超过${props.limit}个!`)
  136. }
  137. // 上传错误提示
  138. const excelUploadError: UploadProps['onError'] = (): void => {
  139. message.error('导入数据失败,请您重新上传!')
  140. }
  141. // 删除上传文件
  142. const handleRemove = (file) => {
  143. const findex = fileList.value.map((f) => f.name).indexOf(file.name)
  144. if (findex > -1) {
  145. fileList.value.splice(findex, 1)
  146. emit('update:modelValue', listToString(fileList.value))
  147. }
  148. }
  149. const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  150. console.log(uploadFile)
  151. }
  152. // 对象转成指定字符串分隔
  153. const listToString = (list: UploadUserFile[], separator?: string) => {
  154. let strs = ''
  155. separator = separator || ','
  156. for (let i in list) {
  157. strs += list[i].url + separator
  158. }
  159. return strs != '' ? strs.substr(0, strs.length - 1) : ''
  160. }
  161. </script>
  162. <style scoped lang="scss">
  163. .upload-file-uploader {
  164. margin-bottom: 5px;
  165. }
  166. :deep(.upload-file-list .el-upload-list__item) {
  167. border: 1px solid #e4e7ed;
  168. line-height: 2;
  169. margin-bottom: 10px;
  170. position: relative;
  171. }
  172. :deep(.el-upload-list__item-file-name) {
  173. max-width: 250px;
  174. }
  175. :deep(.upload-file-list .ele-upload-list__item-content) {
  176. display: flex;
  177. justify-content: space-between;
  178. align-items: center;
  179. color: inherit;
  180. }
  181. :deep(.ele-upload-list__item-content-action .el-link) {
  182. margin-right: 10px;
  183. }
  184. </style>