Upload.vue 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <template>
  2. <div class="uploadImg">
  3. <span class="el-icon-plus"></span>
  4. <input
  5. :accept="accept"
  6. type="file"
  7. class="upload_ipu"
  8. ref="fileLoad"
  9. @change="uploadImg"
  10. />
  11. <img v-if="imgShow" :src="imgSrc" />
  12. </div>
  13. </template>
  14. <script>
  15. export default {
  16. props: {
  17. accept: {
  18. type: String,
  19. default: 'image/jpg,image/jpeg,image/png,image/gif'
  20. }
  21. },
  22. data() {
  23. return {
  24. imgShow: false,
  25. imgSrc: ''
  26. }
  27. },
  28. methods: {
  29. createUrl(file) {
  30. if (window.URL) {
  31. return window.URL.createObjectURL(file)
  32. } else if (window.webkitURL) {
  33. return window.webkitURL.createObjectURL(file)
  34. } else {
  35. return null
  36. }
  37. },
  38. uploadImg() {
  39. let file = this.$refs.fileLoad.files[0]
  40. let size = file.size / 1024 / 1024
  41. if (!this.accept.includes(file.type.toLowerCase())) {
  42. this.$message.error('图片格式不正确!')
  43. return false
  44. }
  45. if (size > 2) {
  46. this.$message.error('图片大小不能超过2MB!')
  47. return false
  48. }
  49. this.imgSrc = this.createUrl(file)
  50. this.imgShow = true
  51. this.$message.success('上传成功!')
  52. }
  53. }
  54. }
  55. </script>
  56. <style lang="scss" scoped>
  57. .uploadImg {
  58. border: 1px dashed #d9d9d9;
  59. border-radius: 6px;
  60. cursor: pointer;
  61. position: relative;
  62. overflow: hidden;
  63. width: 180px;
  64. height: 180px;
  65. transition: all 0.2s;
  66. &:hover {
  67. border-color: #409eff;
  68. }
  69. span {
  70. font-size: 28px;
  71. color: #8c939d;
  72. width: 178px;
  73. height: 178px;
  74. line-height: 178px;
  75. text-align: center;
  76. }
  77. .upload_ipu {
  78. opacity: 0;
  79. width: 100%;
  80. height: 100%;
  81. position: absolute;
  82. cursor: pointer;
  83. top: 0;
  84. left: 0;
  85. z-index: 2;
  86. }
  87. img {
  88. width: 178px;
  89. height: 178px;
  90. position: absolute;
  91. border-radius: 6px;
  92. left: 0;
  93. top: 0;
  94. z-index: 1;
  95. }
  96. }
  97. </style>