Este artículo se basa principalmente en react antDesign UpLoad
componentes y encapsula un componente de carga de imágenes que puede verificar el tamaño y el tamaño.
La documentación oficial de Ant Design ha proporcionado una demostración para verificar el tamaño de la imagen . El código es el siguiente.
function beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
}
El límite de 2M en el documento oficial file.size
se obtiene por bytes y se convierte file.size / 1024 / 1024
. Este parámetro se optimiza aquí y props
se obtiene de él. beforeUpload
Las siguientes actualizaciones se realizan en el método:
let maxSize = this.props.maxSize;
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
let _limitSize = true;
console.log('====>img fileSize', file.size)
// maxSize 这里的maxSize 单位为KB,file.size单位为字节,需要转换下
if (maxSize) {
_limitSize = file.size < maxSize * 1024;
}
Agregue la lógica de verificación del ancho y alto de la imagen y defina un isSize
método denominado aquí. Primero, beforeUpload
pase la información del archivo obtenida dentro como parámetros isSize()
. Se puede dividir en los siguientes pasos:
1. Crear un nuevo elemento de imagen img = new Image();
2. Después de cargar la imagen, obtener el ancho y el alto del elemento de imagen;
3. Verificar el ancho y el alto y regresar el resultado de la verificación;
isSize = (file: {
name: string }) => {
let self = this;
return new Promise((resolve, reject) => {
let width = this.props.width;
let height = this.props.height;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function () {
let valid = false;
console.log('=====>img width', img.width)
console.log('=====>img height', img.height)
valid = img.width == width && img.height == height;
if (!valid) {
message.error(file.name + ' 图片尺寸不符合要求,请修改后重新上传!');
}
self.setState({
_errorSize: !valid,
});
};
img.src = _URL.createObjectURL(file);
});
};
El código para implementar el componente de carga de imágenes es el siguiente:
/*
* @Date 2020/5/11
* @Author zuolinya
* @Description 图片上传
*
*/
import React from 'react';
import {
Upload, message, Button } from 'antd';
import Urls from '@/utils/urls';
import {
baseURL } from "@/utils/requestAxios"
import './index.less';
function getBase64(
img: Blob,
callback: {
(imageUrl: any): void; (arg0: string | ArrayBuffer | null): any },
) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
interface UploadImgType {
width?: number;
height?: number;
maxSize?: number;
onUploadSuccess: Function; //图片上传成功之后的回跳
defaultValue?: any;
}
class UploadImg extends React.Component<UploadImgType, any> {
static defaultProps = {
current: 0,
};
state = {
loading: false,
imageUrl: '',
_errorSize: false,
_errorMax: false,
widthOriginal: '',
heightOriginal: '',
};
handleChange = (info: any) => {
let self = this;
if (info.file.status === 'uploading') {
self.setState({
loading: true });
return;
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj, (imageUrl: any) => {
if (!(self.state._errorSize || self.state._errorMax)) {
self.setState({
imageUrl: imageUrl,
});
// 将图片信息回调给父组件
self.props.onUploadSuccess(info.file);
}
self.setState({
loading: false,
});
});
}
};
beforeUpload = (file: {
type: string; size: number }) => {
let maxSize = this.props.maxSize;
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
}
let _limitSize = true;
console.log('====>img fileSize', file.size)
// maxSize 这里的maxSize 单位为KB,file.size单位为字节,需要转换下
if (maxSize) {
_limitSize = file.size < maxSize * 1024;
}
if (!_limitSize) {
message.error(`图片超过最大尺寸限制 ${
maxSize}KB!`);
this.setState({
_errorMax: true,
});
} else {
this.setState({
_errorMax: false,
})
}
if (this.props.width || this.props.height) {
this.isSize(file);
}
this.setState({
_errorSize: this.state._errorSize && isJpgOrPng,
});
};
isSize = (file: {
name: string }) => {
let self = this;
return new Promise((resolve, reject) => {
let width = this.props.width;
let height = this.props.height;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function () {
let valid = false;
console.log('=====>img width', img.width)
console.log('=====>img height', img.height)
valid = img.width == width && img.height == height;
if (!valid) {
message.error(file.name + ' 图片尺寸不符合要求,请修改后重新上传!');
}
self.setState({
_errorSize: !valid,
});
};
img.src = _URL.createObjectURL(file);
});
};
render() {
const uploadButton = (
<div>
<div className="ant-upload-text">
<Button>{
this.state.loading ? '上传中' : '上传'} </Button>
</div>
</div>
);
let {
imageUrl: _imageUrl } = this.state;
_imageUrl = _imageUrl || this.props.defaultValue;
return (
<Upload
accept="image/png, image/jpeg"
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={
false}
withCredentials
// action为你的上传地址,这里是项目引入地址,可忽略
action={
baseURL + Urls.fetchUploadImage}
beforeUpload={
this.beforeUpload}
onChange={
this.handleChange}
>
{
_imageUrl ? <img src={
_imageUrl} alt="avatar" style={
{
width: '100%' }} /> : uploadButton}
</Upload>
);
}
}
export default UploadImg;
Si tiene alguna pregunta, por favor contácteme ~
Bienvenido a unirse al grupo QQ: