uploader.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <template>
  2. <div class="uploader">
  3. <el-upload
  4. class="avatar-uploader"
  5. action="#"
  6. :show-file-list="false"
  7. :multiple="false"
  8. accept="image/png, image/jpeg"
  9. :before-upload="handleFileChange"
  10. >
  11. <i v-if="imageUrl" class="el-icon-delete avatar-uploader-icon" @click.stop="handleDeleteFile"></i>
  12. <img v-if="imageUrl" :src="imageUrl" class="avatar" />
  13. <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  14. <span v-if="title" class="title">{{title}}</span>
  15. </el-upload>
  16. </div>
  17. </template>
  18. <script>
  19. export default {
  20. props: ["imageUrl", "title"],
  21. components: {},
  22. data() {
  23. return {
  24. uploading: false
  25. };
  26. },
  27. computed: {},
  28. mounted() {},
  29. methods: {
  30. handleDeleteFile() {
  31. this.$emit("change", "");
  32. },
  33. handleFileChange(file) {
  34. const file = e.target.files[0];
  35. // if (file.size / 1024 > 500) {
  36. // this.$message.error("图片大小不得超过500k,请重新选择");
  37. // return false;
  38. // }
  39. const formData = new FormData();
  40. formData.append("file", file);
  41. formData.append("original_filename", file.name);
  42. this.uploading = true;
  43. this.$axios
  44. .$post(`/upload_image`, formData, {
  45. headers: { "Content-Type": "multipart/form-data" }
  46. })
  47. .then(res => {
  48. this.$emit("change", res.filename);
  49. })
  50. .finally(() => {
  51. this.uploading = false;
  52. });
  53. }
  54. }
  55. };
  56. </script>
  57. <style lang="scss">
  58. .uploader {
  59. position: relative;
  60. padding: 20px;
  61. width: 740px;
  62. background: #fff;
  63. .el-icon-delete {
  64. display: none;
  65. }
  66. .avatar-uploader .el-upload {
  67. width: 160px;
  68. height: 110px;
  69. border: 1px dashed #d9d9d9;
  70. border-radius: 6px;
  71. cursor: pointer;
  72. position: relative;
  73. overflow: hidden;
  74. img {
  75. width: 100%;
  76. height: auto;
  77. object-fit: contain;
  78. object-position: top left;
  79. }
  80. }
  81. .avatar-uploader .el-upload:hover {
  82. border-color: #409eff;
  83. .el-icon-delete {
  84. display: block;
  85. }
  86. }
  87. .avatar-uploader-icon {
  88. position: absolute;
  89. top: 0;
  90. left: 0;
  91. font-size: 28px;
  92. color: #fff;
  93. width: 160px;
  94. height: 110px;
  95. line-height: 110px;
  96. text-align: center;
  97. background: rgba(1, 1, 1, 0.3);
  98. :hover {
  99. color: #409eff;
  100. }
  101. }
  102. .avatar {
  103. width: 178px;
  104. height: 178px;
  105. display: block;
  106. }
  107. }
  108. </style>