index.vue 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. multiple
  5. :action="uploadFileUrl"
  6. :before-upload="handleBeforeUpload"
  7. :file-list="fileList"
  8. :data="data"
  9. :limit="limit"
  10. :on-error="handleUploadError"
  11. :on-exceed="handleExceed"
  12. :on-success="handleUploadSuccess"
  13. :show-file-list="false"
  14. :headers="headers"
  15. class="upload-file-uploader"
  16. ref="fileUpload"
  17. v-if="!disabled"
  18. >
  19. <!-- 上传按钮 -->
  20. <el-button type="primary">选取文件</el-button>
  21. </el-upload>
  22. <!-- 上传提示 -->
  23. <div class="el-upload__tip" v-if="showTip && !disabled">
  24. 请上传
  25. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  26. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  27. 的文件
  28. </div>
  29. <!-- 文件列表 -->
  30. <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
  31. <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
  32. <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
  33. <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
  34. </el-link>
  35. <div class="ele-upload-list__item-content-action">
  36. <el-link :underline="false" @click="handleDelete(index)" type="danger" v-if="!disabled">&nbsp;删除</el-link>
  37. </div>
  38. </li>
  39. </transition-group>
  40. </div>
  41. </template>
  42. <script setup>
  43. import { getToken } from "@/utils/auth"
  44. import Sortable from 'sortablejs'
  45. const props = defineProps({
  46. modelValue: [String, Object, Array],
  47. // 上传接口地址
  48. action: {
  49. type: String,
  50. default: "/common/upload"
  51. },
  52. // 上传携带的参数
  53. data: {
  54. type: Object
  55. },
  56. // 数量限制
  57. limit: {
  58. type: Number,
  59. default: 5
  60. },
  61. // 大小限制(MB)
  62. fileSize: {
  63. type: Number,
  64. default: 5
  65. },
  66. // 文件类型, 例如['png', 'jpg', 'jpeg']
  67. fileType: {
  68. type: Array,
  69. default: () => ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf"]
  70. },
  71. // 是否显示提示
  72. isShowTip: {
  73. type: Boolean,
  74. default: true
  75. },
  76. // 禁用组件(仅查看文件)
  77. disabled: {
  78. type: Boolean,
  79. default: false
  80. },
  81. // 拖动排序
  82. drag: {
  83. type: Boolean,
  84. default: true
  85. }
  86. })
  87. const { proxy } = getCurrentInstance()
  88. const emit = defineEmits()
  89. const number = ref(0)
  90. const uploadList = ref([])
  91. const baseUrl = import.meta.env.VITE_APP_BASE_API
  92. const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action) // 上传文件服务器地址
  93. const headers = ref({ Authorization: "Bearer " + getToken() })
  94. const fileList = ref([])
  95. const showTip = computed(
  96. () => props.isShowTip && (props.fileType || props.fileSize)
  97. )
  98. watch(() => props.modelValue, val => {
  99. if (val) {
  100. let temp = 1
  101. // 首先将值转为数组
  102. const list = Array.isArray(val) ? val : props.modelValue.split(',')
  103. // 然后将数组转为对象数组
  104. fileList.value = list.map(item => {
  105. if (typeof item === "string") {
  106. item = { name: item, url: item }
  107. }
  108. item.uid = item.uid || new Date().getTime() + temp++
  109. return item
  110. })
  111. } else {
  112. fileList.value = []
  113. return []
  114. }
  115. },{ deep: true, immediate: true })
  116. // 上传前校检格式和大小
  117. function handleBeforeUpload(file) {
  118. // 校检文件类型
  119. if (props.fileType.length) {
  120. const fileName = file.name.split('.')
  121. const fileExt = fileName[fileName.length - 1]
  122. const isTypeOk = props.fileType.indexOf(fileExt) >= 0
  123. if (!isTypeOk) {
  124. proxy.$modal.msgError(`文件格式不正确,请上传${props.fileType.join("/")}格式文件!`)
  125. return false
  126. }
  127. }
  128. // 校检文件名是否包含特殊字符
  129. if (file.name.includes(',')) {
  130. proxy.$modal.msgError('文件名不正确,不能包含英文逗号!')
  131. return false
  132. }
  133. // 校检文件大小
  134. if (props.fileSize) {
  135. const isLt = file.size / 1024 / 1024 < props.fileSize
  136. if (!isLt) {
  137. proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`)
  138. return false
  139. }
  140. }
  141. proxy.$modal.loading("正在上传文件,请稍候...")
  142. number.value++
  143. return true
  144. }
  145. // 文件个数超出
  146. function handleExceed() {
  147. proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
  148. }
  149. // 上传失败
  150. function handleUploadError(err) {
  151. proxy.$modal.msgError("上传文件失败")
  152. proxy.$modal.closeLoading()
  153. }
  154. // 上传成功回调
  155. function handleUploadSuccess(res, file) {
  156. if (res.code === 200) {
  157. uploadList.value.push({ name: res.fileName, url: res.fileName })
  158. uploadedSuccessfully()
  159. } else {
  160. number.value--
  161. proxy.$modal.closeLoading()
  162. proxy.$modal.msgError(res.msg)
  163. proxy.$refs.fileUpload.handleRemove(file)
  164. uploadedSuccessfully()
  165. }
  166. }
  167. // 删除文件
  168. function handleDelete(index) {
  169. fileList.value.splice(index, 1)
  170. emit("update:modelValue", listToString(fileList.value))
  171. }
  172. // 上传结束处理
  173. function uploadedSuccessfully() {
  174. if (number.value > 0 && uploadList.value.length === number.value) {
  175. fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
  176. uploadList.value = []
  177. number.value = 0
  178. emit("update:modelValue", listToString(fileList.value))
  179. proxy.$modal.closeLoading()
  180. }
  181. }
  182. // 获取文件名称
  183. function getFileName(name) {
  184. // 如果是url那么取最后的名字 如果不是直接返回
  185. if (name.lastIndexOf("/") > -1) {
  186. return name.slice(name.lastIndexOf("/") + 1)
  187. } else {
  188. return name
  189. }
  190. }
  191. // 对象转成指定字符串分隔
  192. function listToString(list, separator) {
  193. let strs = ""
  194. separator = separator || ","
  195. for (let i in list) {
  196. if (list[i].url) {
  197. strs += list[i].url + separator
  198. }
  199. }
  200. return strs != '' ? strs.substr(0, strs.length - 1) : ''
  201. }
  202. // 初始化拖拽排序
  203. onMounted(() => {
  204. if (props.drag) {
  205. nextTick(() => {
  206. const element = document.querySelector('.upload-file-list')
  207. Sortable.create(element, {
  208. ghostClass: 'file-upload-darg',
  209. onEnd: (evt) => {
  210. const movedItem = fileList.value.splice(evt.oldIndex, 1)[0]
  211. fileList.value.splice(evt.newIndex, 0, movedItem)
  212. emit('update:modelValue', listToString(fileList.value))
  213. }
  214. })
  215. })
  216. }
  217. })
  218. </script>
  219. <style scoped lang="scss">
  220. .file-upload-darg {
  221. opacity: 0.5;
  222. background: #c8ebfb;
  223. }
  224. .upload-file-uploader {
  225. margin-bottom: 5px;
  226. }
  227. .upload-file-list .el-upload-list__item {
  228. border: 1px solid #e4e7ed;
  229. line-height: 2;
  230. margin-bottom: 10px;
  231. position: relative;
  232. transition: none !important;
  233. }
  234. .upload-file-list .ele-upload-list__item-content {
  235. display: flex;
  236. justify-content: space-between;
  237. align-items: center;
  238. color: inherit;
  239. }
  240. .ele-upload-list__item-content-action .el-link {
  241. margin-right: 10px;
  242. }
  243. </style>