image.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <template>
  2. <div>
  3. <el-upload
  4. class="image-uploader"
  5. :action="`${path}/fileUploadAndDownload/upload`"
  6. :headers="{ 'x-token': token }"
  7. :show-file-list="false"
  8. :on-success="handleImageSuccess"
  9. :before-upload="beforeImageUpload"
  10. :multiple="false"
  11. >
  12. <img v-if="imageUrl" :src="showImageUrl" class="image">
  13. <i v-else class="el-icon-plus image-uploader-icon" />
  14. </el-upload>
  15. </div>
  16. </template>
  17. <script>
  18. const path = import.meta.env.VITE_BASE_API
  19. import { mapGetters } from 'vuex'
  20. import ImageCompress from '@/utils/image'
  21. export default {
  22. name: 'UploadImage',
  23. model: {
  24. prop: 'imageUrl',
  25. event: 'change'
  26. },
  27. props: {
  28. imageUrl: {
  29. type: String,
  30. default: ''
  31. },
  32. fileSize: {
  33. type: Number,
  34. default: 2048 // 2M 超出后执行压缩
  35. },
  36. maxWH: {
  37. type: Number,
  38. default: 1920 // 图片长宽上限
  39. }
  40. },
  41. data() {
  42. return {
  43. path: path
  44. }
  45. },
  46. computed: {
  47. ...mapGetters('user', ['userInfo', 'token']),
  48. showImageUrl() {
  49. return (this.imageUrl && this.imageUrl.slice(0, 4) !== 'http') ? path + this.imageUrl : this.imageUrl
  50. }
  51. },
  52. methods: {
  53. beforeImageUpload(file) {
  54. const isRightSize = file.size / 1024 < this.fileSize
  55. if (!isRightSize) {
  56. // 压缩
  57. const compress = new ImageCompress(file, this.fileSize, this.maxWH)
  58. return compress.compress()
  59. }
  60. return isRightSize
  61. },
  62. handleImageSuccess(res) {
  63. // this.imageUrl = URL.createObjectURL(file.raw);
  64. const { data } = res
  65. if (data.file) {
  66. this.$emit('change', data.file.url)
  67. this.$emit('on-success')
  68. }
  69. }
  70. }
  71. }
  72. </script>
  73. <style lang="scss" scoped>
  74. .image-uploader {
  75. border: 1px dashed #d9d9d9;
  76. width: 180px;
  77. border-radius: 6px;
  78. cursor: pointer;
  79. position: relative;
  80. overflow: hidden;
  81. }
  82. .image-uploader {
  83. border-color: #409eff;
  84. }
  85. .image-uploader-icon {
  86. font-size: 28px;
  87. color: #8c939d;
  88. width: 178px;
  89. height: 178px;
  90. line-height: 178px;
  91. text-align: center;
  92. }
  93. .image {
  94. width: 178px;
  95. height: 178px;
  96. display: block;
  97. }
  98. </style>