index.vue 7.3 KB

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