vue+element+upload文件上传前校验类型和大小、抛出异常或错误、正则表达式、转小写、截取字符串、throw、RegExp、toLowerCase、lastIndexOf、includes


JS版本(闭包)

实现函数(方法)

function TypeAndSizeVerification(accept = '.jpg, .jpeg, .png, .gif', setFileSize = 10) {
    
    
	if (typeof accept !== 'string') throw new Error(`${
      
      typeof accept} is not the expected type, but the string type is expected.`);
	if (typeof setFileSize !== 'number') throw new Error(`${
      
      typeof accept} is not the expected type, but the string type is expected.`);
	
	// 去除所有空格的正则表达式
	let reg = /[\t\r\f\n\s]*/g,
		// 文件后缀名
		targetArray = undefined;
	
	targetArray = accept.split(reg);
	targetArray = targetArray.join('');
	targetArray = targetArray.split(',');
	
	// 去除点,并且转为小写
	targetArray = targetArray.map(item => {
    
    
		item = item.substring(1);
		item = item.toLowerCase();
		
		return item;
	});
	
	return function (fileType = '', fileSize = 0) {
    
    
		if (typeof fileType !== 'string') throw new Error(`${
      
      typeof fileType} is not the expected type, but the string type is expected.`);
		if (typeof fileSize !== 'number') throw `${
      
      typeof fileSize} is not the expected type, but the number type is expected.`;
		
		if (fileType.lastIndexOf(".") !== -1) {
    
    
			fileType = fileType.substring(fileType.lastIndexOf(".") + 1);
		} else if (fileType.lastIndexOf("/") !== -1) {
    
    
			fileType = fileType.split('/');
			fileType = fileType[1];
		} else {
    
    
			throw `'${
      
      fileType}' not the correct file type.`;
		}
		
		fileType = fileType.toLowerCase();
		
		// 检测文件类型
		let isFileType = targetArray.includes(fileType),
			// 文件大小为20M
			isFileSize = fileSize / 1024 / 1024 < setFileSize;
		
		return isFileType && isFileSize;
	}
}

代码解析

关于正则表达式的书写方式
1、let reg = /[\t\r\f\n\s]*/g;
2、let reg = new RegExp("\[\\t\\r\\f\\n\\s\]*", "g");
3、let reg = new RegExp(/[\t\r\f\n\s]*/, "g");


代码简写方式
targetArray = accept.split(reg);
targetArray = targetArray.join('');
targetArray = targetArray.split(',');

以上三行代码可以简写为以下方式,只是个人习惯一步一步实现
targetArray = accept.split(reg).join("").split(",");


正确参数的方法执行示例

let TASV = new TypeAndSizeVerification('.jpg, .jpeg, .png, .GIF', 20);
console.log(TASV('guiling.jpg', 1873));
// true
console.log(TASV('lingyi.txt', 1024));
// false
console.log(TASV('image/png', 1024));
// true
console.log(TASV('image/jpeg', 86852398));
// false
console.log(TASV('guiling.JPG', 1024));
// true
console.log(TASV('lingyi.gif', 1024));
// true

错误参数的方法执行示例

let TASV = new TypeAndSizeVerification(908);
// Uncaught Error: number is not the expected type, but the string type is expected.
console.log(TASV([1, 2], 86852398));
// Uncaught Error: object is not the expected type, but the string type is expected.
console.log(TASV('image/jpg', '86852398'));
// Uncaught string is not the expected type, but the number type is expected.
console.log(TASV('guilinglingyi', 1024));
// Uncaught 'guilinglingyi' not the correct file type.

TS版本(构造类)

实现函数(方法)

export class TypeAndSizeVerification {
    
    
    targetArray: any;
    setFileSize: number;

    constructor(accept: string = '.jpg, .jpeg, .png, .gif', setFileSize: number = 10) {
    
    
        if (typeof accept !== 'string') throw new Error(`${
      
      typeof accept} is not the expected type, but the string type is expected.`);
        if (typeof setFileSize !== 'number') throw new Error(`${
      
      typeof accept} is not the expected type, but the string type is expected.`);

        this.targetArray = accept;
        this.setFileSize = setFileSize;

        this.handleType();
    }

    // 被private修饰的方法属于私有方法,只能在声明它的类内部访问,
    // 无法从类的外部或子类中访问。
    private handleType(): void {
    
    
        // 去除所有空格的正则表达式
        let reg: RegExp = /[\t\r\f\n\s]*/g;

        this.targetArray = this.targetArray.split(reg);
        this.targetArray = this.targetArray.join('');
        this.targetArray = this.targetArray.split(',');

        // 去除点,并且转为小写
        this.targetArray = this.targetArray.map((item: string) => {
    
    
            item = item.substring(1);
            item = item.toLowerCase();

            return item;
        });
    }

    handleResult(fileType: any = '', fileSize: number = 0): boolean {
    
    
        if (typeof fileType !== 'string') throw new Error(`${
      
      typeof fileType} is not the expected type, but the string type is expected.`);
        if (typeof fileSize !== 'number') throw `${
      
      typeof fileSize} is not the expected type, but the number type is expected.`;

        if (fileType.lastIndexOf(".") !== -1) {
    
    
            fileType = fileType.substring(fileType.lastIndexOf(".") + 1);
        } else if (fileType.lastIndexOf("/") !== -1) {
    
    
            fileType = fileType.split('/');
            fileType = fileType[1];
        } else {
    
    
            throw `'${
      
      fileType}' not the correct file type.`;
        }

        fileType = fileType.toLowerCase();

        // 检测文件类型
        let isFileType: boolean = this.targetArray.includes(fileType),
            // 文件大小为20M
            isFileSize: boolean = fileSize / 1024 / 1024 < this.setFileSize;

        return isFileType && isFileSize;
    }
}

使用构造类

import {
    
     TypeAndSizeVerification } from '@/utils/typeAndSizeVerification';

let accept = ref(".jpg, .jpeg, .png"),
    TASV = new TypeAndSizeVerification(accept.value, 20);

// file.name
console.log(TASV.handleResult('test.txt'));
// file.type
console.log(TASV.handleResult('image/png'));

代码解析
private

private修饰的方法属于私有方法,只能在声明它的类内部访问,无法从类的外部或子类中访问。

class MyClass {
     
     
    private privateMethod() {
     
     
        // 私有方法的实现
    }

    public publicMethod() {
     
     
        // 公共方法可以调用私有方法
        this.privateMethod();
    }
}

const instance = new MyClass();
// 可以调用公共方法
instance.publicMethod();
// 无法调用私有方法,会导致编译错误
// instance.privateMethod();

protected

protected修饰的方法是受保护方法,只能在声明它的类及其子类内部访问,无法从类的外部访问。这使得方法对于类的继承体系中的子类是可见的。

class MyBaseClass {
     
     
    protected protectedMethod() {
     
     
        // 受保护方法的实现
    }
}

class MyDerivedClass extends MyBaseClass {
     
     
    public useProtectedMethod() {
     
     
    	// 子类可以调用受保护方法
        this.protectedMethod();
    }
}

const baseInstance = new MyBaseClass();
// 无法调用受保护方法,会导致编译错误
// baseInstance.protectedMethod();

const derivedInstance = new MyDerivedClass();
// 可以调用使用受保护方法的公共方法
derivedInstance.useProtectedMethod();

throw和throw new Error()对比

throw new Error()抛出的异常更加直观优雅,不像throw抛出的异常那么杂糅。建议多使用throw new Error()

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/132309715