image.vue 2.0 KB

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