index.vue 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. multiple
  5. :action="uploadImgUrl"
  6. list-type="picture-card"
  7. :on-success="handleUploadSuccess"
  8. :before-upload="handleBeforeUpload"
  9. :data="data"
  10. :limit="limit"
  11. :on-error="handleUploadError"
  12. :on-exceed="handleExceed"
  13. ref="imageUpload"
  14. :on-remove="handleDelete"
  15. :show-file-list="true"
  16. :headers="headers"
  17. :file-list="fileList"
  18. :on-preview="handlePictureCardPreview"
  19. :class="{hide: this.fileList.length >= this.limit}"
  20. >
  21. <i class="el-icon-plus"></i>
  22. </el-upload>
  23. <!-- 上传提示 -->
  24. <div class="el-upload__tip" slot="tip" v-if="showTip">
  25. 请上传
  26. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  27. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  28. 的文件
  29. </div>
  30. <el-dialog
  31. :visible.sync="dialogVisible"
  32. title="预览"
  33. width="800"
  34. append-to-body
  35. >
  36. <img
  37. :src="dialogImageUrl"
  38. style="display: block; max-width: 100%; margin: 0 auto"
  39. />
  40. </el-dialog>
  41. </div>
  42. </template>
  43. <script>
  44. import { getToken } from "@/utils/auth"
  45. import { isExternal } from "@/utils/validate"
  46. import Sortable from 'sortablejs'
  47. export default {
  48. props: {
  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: () => ["png", "jpg", "jpeg"]
  73. },
  74. // 是否显示提示
  75. isShowTip: {
  76. type: Boolean,
  77. default: true
  78. },
  79. // 拖动排序
  80. drag: {
  81. type: Boolean,
  82. default: true
  83. }
  84. },
  85. data() {
  86. return {
  87. number: 0,
  88. uploadList: [],
  89. dialogImageUrl: "",
  90. dialogVisible: false,
  91. hideUpload: false,
  92. baseUrl: process.env.VUE_APP_BASE_API,
  93. uploadImgUrl: process.env.VUE_APP_BASE_API + this.action, // 上传的图片服务器地址
  94. headers: {
  95. Authorization: "Bearer " + getToken(),
  96. },
  97. fileList: []
  98. }
  99. },
  100. mounted() {
  101. if (this.drag) {
  102. this.$nextTick(() => {
  103. const element = document.querySelector('.el-upload-list')
  104. Sortable.create(element, {
  105. onEnd: (evt) => {
  106. const movedItem = this.fileList.splice(evt.oldIndex, 1)[0]
  107. this.fileList.splice(evt.newIndex, 0, movedItem)
  108. this.$emit("input", this.listToString(this.fileList))
  109. }
  110. })
  111. })
  112. }
  113. },
  114. watch: {
  115. value: {
  116. handler(val) {
  117. if (val) {
  118. // 首先将值转为数组
  119. const list = Array.isArray(val) ? val : this.value.split(',')
  120. // 然后将数组转为对象数组
  121. this.fileList = list.map(item => {
  122. if (typeof item === "string") {
  123. if (item.indexOf(this.baseUrl) === -1 && !isExternal(item)) {
  124. item = { name: this.baseUrl + item, url: this.baseUrl + item }
  125. } else {
  126. item = { name: item, url: item }
  127. }
  128. }
  129. return item
  130. })
  131. } else {
  132. this.fileList = []
  133. return []
  134. }
  135. },
  136. deep: true,
  137. immediate: true
  138. }
  139. },
  140. computed: {
  141. // 是否显示提示
  142. showTip() {
  143. return this.isShowTip && (this.fileType || this.fileSize)
  144. },
  145. },
  146. methods: {
  147. // 上传前loading加载
  148. handleBeforeUpload(file) {
  149. let isImg = false
  150. if (this.fileType.length) {
  151. let fileExtension = ""
  152. if (file.name.lastIndexOf(".") > -1) {
  153. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1)
  154. }
  155. isImg = this.fileType.some(type => {
  156. if (file.type.indexOf(type) > -1) return true
  157. if (fileExtension && fileExtension.indexOf(type) > -1) return true
  158. return false
  159. })
  160. } else {
  161. isImg = file.type.indexOf("image") > -1
  162. }
  163. if (!isImg) {
  164. this.$modal.msgError(`文件格式不正确,请上传${this.fileType.join("/")}图片格式文件!`)
  165. return false
  166. }
  167. if (file.name.includes(',')) {
  168. this.$modal.msgError('文件名不正确,不能包含英文逗号!')
  169. return false
  170. }
  171. if (this.fileSize) {
  172. const isLt = file.size / 1024 / 1024 < this.fileSize
  173. if (!isLt) {
  174. this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
  175. return false
  176. }
  177. }
  178. this.$modal.loading("正在上传图片,请稍候...")
  179. this.number++
  180. },
  181. // 文件个数超出
  182. handleExceed() {
  183. this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
  184. },
  185. // 上传成功回调
  186. handleUploadSuccess(res, file) {
  187. if (res.code === 200) {
  188. this.uploadList.push({ name: res.fileName, url: res.fileName })
  189. this.uploadedSuccessfully()
  190. } else {
  191. this.number--
  192. this.$modal.closeLoading()
  193. this.$modal.msgError(res.msg)
  194. this.$refs.imageUpload.handleRemove(file)
  195. this.uploadedSuccessfully()
  196. }
  197. },
  198. // 删除图片
  199. handleDelete(file) {
  200. const findex = this.fileList.map(f => f.name).indexOf(file.name)
  201. if (findex > -1) {
  202. this.fileList.splice(findex, 1)
  203. this.$emit("input", this.listToString(this.fileList))
  204. }
  205. },
  206. // 上传失败
  207. handleUploadError() {
  208. this.$modal.msgError("上传图片失败,请重试")
  209. this.$modal.closeLoading()
  210. },
  211. // 上传结束处理
  212. uploadedSuccessfully() {
  213. if (this.number > 0 && this.uploadList.length === this.number) {
  214. this.fileList = this.fileList.concat(this.uploadList)
  215. this.uploadList = []
  216. this.number = 0
  217. this.$emit("input", this.listToString(this.fileList))
  218. this.$modal.closeLoading()
  219. }
  220. },
  221. // 预览
  222. handlePictureCardPreview(file) {
  223. this.dialogImageUrl = file.url
  224. this.dialogVisible = true
  225. },
  226. // 对象转成指定字符串分隔
  227. listToString(list, separator) {
  228. let strs = ""
  229. separator = separator || ","
  230. for (let i in list) {
  231. if (list[i].url) {
  232. strs += list[i].url.replace(this.baseUrl, "") + separator
  233. }
  234. }
  235. return strs != '' ? strs.substr(0, strs.length - 1) : ''
  236. }
  237. }
  238. }
  239. </script>
  240. <style scoped lang="scss">
  241. // .el-upload--picture-card 控制加号部分
  242. ::v-deep.hide .el-upload--picture-card {
  243. display: none;
  244. }
  245. // 去掉动画效果
  246. ::v-deep .el-list-enter-active,
  247. ::v-deep .el-list-leave-active {
  248. transition: all 0s;
  249. }
  250. ::v-deep .el-list-enter, .el-list-leave-active {
  251. opacity: 0;
  252. transform: translateY(0);
  253. }
  254. </style>