index.vue 7.3 KB

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