ng.ant.design上传图片校验
html:
<div class="clearfix upload_containter">
<nz-upload class='upload-btn' [nzCustomRequest]="customReq" [nzName]="'DrugImages'"
[nzBeforeUpload]="beforeUpload" [(nzFileList)]="drugImagesList" nzListType="picture-card"
[nzShowButton]="drugImagesList.length<5 && canEditor" [nzShowUploadList]="showUploadList"
[nzPreview]="handlePreview" [nzRemove]='removeDrugImg'>
<i nz-icon nzType="plus"></i>
<div class="ant-upload-text">点击上传</div>
</nz-upload>
</div>
ts:
import { CheckImage } from '/shared/utils/CheckImage.base';
/**
* @description: 图片上传前校验
* @params: {item: UploadXHRArgs}
* @return:
*/
beforeUpload = (file: File) => {
return new Observable(observer => {
const isJPG = file.type === 'image/jpeg';
const isPNg = file.type === 'image/png';
const isJPg = file.type === 'image/jpg';
if (!isJPG && !isPNg && !isJPg) {
this.nzMsg.error('只能上传jpeg,png,jpg格式图片');
return;
}
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isLt1M) {
this.nzMsg.error('图片大小只能小于 1MB!');
return;
}
// check height
CheckImage.checkImageDimension(file).then(dimensionRes => {
if (!dimensionRes) {
this.nzMsg.error('请上传大小为800*800px的图片');
return;
}
// observer.next(isJPG && isLt1M && dimensionRes);
// observer.complete();
observer.next(file);
});
});
};
CheckImage 文件
export class CheckImage {
/**
* @description: 校验上传图片大小
* {file} 上传图片对象
* @return: boolean
*/
public static checkImageDimension(file: File): Promise<boolean> {
return new Promise(resolve => {
const img = new Image(); // create image
img.src = window.URL.createObjectURL(file);
img.onload = () => {
const width = img.naturalWidth;
const height = img.naturalHeight;
window.URL.revokeObjectURL(img.src!);
resolve(width === height && width === 800);
};
});
}
}