index.vue 7.2 KB

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