美文网首页
elementui,el-upload中获取图片宽高

elementui,el-upload中获取图片宽高

作者: 随风飞2019 | 来源:发表于2021-05-05 09:07 被阅读0次
    beforeImgUpload(file) {
                let reader = new FileReader();
                reader.onload = function (e) {
                    let txt = e.target.result
                    let img = document.createElement("img")
                    img.src = txt
                    img.onload = function () {
                        console.log("宽度:",img.width);
                        console.log("高度:",img.height);
                    }
                };
                reader.readAsDataURL(file);
    },
    
    

    下面是别人写的一段代码,对图片进行校验的

    
    beforeAvatarUpload(file) {
        // 上传图片前处理函数
        const isJPG =
            file.type === "image/jpeg" ||
            file.type === "image/png" ||
            file.type === "image/gif";
        const isLt2M = file.size / 1024 / 1024 < 2;
        let that = this;
        let isAllow = false;
        if (!isJPG) {
            this.$message.error("上传头像图片只能是 jpg、png、gif 格式!");
        }
        if (!isLt2M) {
            this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        const isSize = new Promise(function(resolve, reject) {
            let width = 750;
            let height = 420;
            let _URL = window.URL || window.webkitURL;
            let image = new Image();
            image.onload = function() {
              let valid = image.width == width && image.height == height;
              valid ? resolve() : reject();
            };
            image.src = _URL.createObjectURL(file);
        }).then(
            () => {
              return file;
            },
            () => {
              this.$message.error("上传头像图片尺寸不符合,只能是750*420!");
              return Promise.reject();
            }
          );
        return isJPG && isLt2M && isSize;
    }
    

    相关文章

      网友评论

          本文标题:elementui,el-upload中获取图片宽高

          本文链接:https://www.haomeiwen.com/subject/owrkdltx.html