Commit 4185b9b2 authored by 武广's avatar 武广

feat: 添加图片校验

parent d1c26369
const isProduction = process.env.NODE_ENV === 'production';
const isPre = process.env.PRE_ENV === 'pre';
const environment = 'yxm2';
const environment = 'yxm';
const envAPi = {
api: `https://security-${environment}.liangkebang.net`, //'https://security-xyqb.liangkebang.net',
kdspOpApi: `https://sc-merchant-api-${environment}.liangkebang.net`,
......
import { PlusOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { validImageType } from '@/utils/img.valid';
import { Modal, Upload, notification, Spin, Icon, Button } from 'antd';
import React, { useState, useEffect, useRef, forwardRef } from 'react';
import lodash from 'lodash';
......@@ -99,21 +100,29 @@ const UploadImage = forwardRef((props, ref) => {
warningTip(`[${file.name}] 图片不可以大于2MB`);
resolve(null);
}
getBase64(file, url => {
const image = new Image();
image.addEventListener('load', () => {
const { width } = image;
const { height } = image;
file.width = width;
file.height = height;
file.LtMB = LtMB;
resolve(file);
});
image.addEventListener('error', () => {
warningTip(`${file.name}图片上传失败!`);
const curType = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
validImageType(file, curType).then(res => {
if (!res) {
warningTip(`[${file.name}] 请上传正确图片!`);
resolve(null);
});
image.src = url;
} else {
getBase64(file, url => {
const image = new Image();
image.addEventListener('load', () => {
const { width } = image;
const { height } = image;
file.width = width;
file.height = height;
file.LtMB = LtMB;
resolve(file);
});
image.addEventListener('error', () => {
warningTip(`${file.name}图片上传失败!`);
resolve(null);
});
image.src = url;
});
}
});
});
......
/**
* 真实文件格式(前4个字节)
*/
export const ImgExt2Hex = {
jpg: ['ffd8ffe0', 'ffd8ffe1', 'ffd8ffe2', 'ffd8ffe3'],
jpeg: ['ffd8ffe0', 'ffd8ffe1', 'ffd8ffe2', 'ffd8ffe3'],
png: ['89504e47'],
};
/**
* 检测图片是否是预期的类型
* @param {File} imgFile 图片文件对象
* @param {string} imgExt 文件预期真实类型
* @return {boolean} 文件类型是否和预期一致
*/
export const validImageType = (imgFile, imgExt) => {
const FR = new FileReader();
return new Promise(resolve => {
FR.onload = e => {
const { type } = imgFile;
const correctExtHex = ImgExt2Hex[imgExt];
const af = e.target.result;
const view = new DataView(af);
const first4Byte = view.getUint32(0, false); // 获取32bit数
const hexValue = Number(first4Byte).toString(16);
if (!type || !correctExtHex) {
return resolve(false);
}
return resolve(correctExtHex.indexOf(hexValue) > -1);
};
FR.readAsArrayBuffer(imgFile);
});
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment