限制图片上传时的文件大小和尺寸

const beforeUpload = (file: any) => {    
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    // 上传图片前处理函数
    const isSize = new Promise(function(resolve, reject) {
        let width = 240;
        let height = 240;
        let _URL = window.URL || window.webkitURL;
        let image = new Image();
        image.onload = function() {
            let valid = image.width > width && image.height > height && image.width == image.height;
            valid ? resolve() : reject();
        };
        image.src = _URL.createObjectURL(file);
    }).then(
        () => {
            return file;
        },
        () => {
            ElMessage.error("请上传240*240px以上,1:1的图标");
            return Promise.reject();
        }
    );

    return isLt2M && isSize;
}
posted @ 2023-03-07 16:31  郭大蛋子  阅读(85)  评论(0编辑  收藏  举报