Преглед изворни кода

上传文件/图片组件 添加图片大小判断

DESKTOP-O04BTUJ\muzen пре 3 година
родитељ
комит
ebca2b976a
1 измењених фајлова са 56 додато и 11 уклоњено
  1. 56 11
      src/components/Upload/index.vue

+ 56 - 11
src/components/Upload/index.vue

@@ -44,6 +44,11 @@ export default {
     title: {
       type: String,
       default: '文件上传'
+    },
+    // 图片尺寸
+    measure: {
+      type: String,
+      default: ''
     }
   },
   watch: {
@@ -80,22 +85,38 @@ export default {
       // 显示图片
       newUrl: this.url,
       // 传给父级的参数
-      form: {}
+      form: {},
+      // 上传图片的尺寸
+      width: Number(this.measure.split('*')[0]),
+      height: Number(this.measure.split('*')[1])
     }
   },
   mounted() {
     this.newUrl = this.url ? this.url : ''
     this.hidden = this.url ? false : true
+    console.log(this.height);
   },
   methods: {
     // 上传之前
-    beforeUpload(file) {
-      this.data.multipartFile = file
-      this.name = file.name
-      if (this.listType === 'text') {
-        this.form.size = file.size
+    async beforeUpload(file) {
+      if (this.measure) {
+        await this.measureChecked(file).then((res) => {
+          this.data.multipartFile = res ? file : ''
+          this.name = res ? file.name : ''
+          if (this.listType === 'text') {
+            this.form.size = res ? file.size : ''
+          } else {
+            this.hidden = res ? false : true
+          }
+        })
       } else {
-        this.hidden = false
+        this.data.multipartFile = file
+        this.name = file.name
+        if (this.listType === 'text') {
+          this.form.size = file.size
+        } else {
+          this.hidden = false
+        }
       }
     },
     // 上传过程中
@@ -142,6 +163,26 @@ export default {
       } else {
         return false
       }
+    },
+
+    // 判断图片尺寸
+    measureChecked(file) {
+      return new Promise((resolve, reject) => {
+        let reader = new FileReader()
+        reader.readAsDataURL(file)
+        reader.onload = () => {
+          let img = new Image()
+          img.src = reader.result
+          img.onload = () => {
+            if (img.width !== this.width && img.height !== this.height) {
+              this.$message.error(`请上传${this.measure}尺寸的图片`)
+              resolve(false)
+            } else {
+              resolve(true)
+            }
+          }
+        }
+      })
     }
   }
 }
@@ -151,14 +192,17 @@ export default {
 .upload {
   display: inline-block;
 
-  .el-button{
+  .el-button {
     margin: 0;
   }
 
   .upload-image {
     position: relative;
     width: 148px;
-    height: 148px;
+
+    .el-image {
+      display: block;
+    }
 
     .el-icon-delete {
       position: absolute;
@@ -171,9 +215,10 @@ export default {
       color: #fff;
       transition: all 0.3s;
       font-size: 24px;
-      text-align: center;
-      line-height: 148px;
       opacity: 0;
+      display: flex;
+      justify-content: center;
+      align-items: center;
     }
 
     i:hover {