Commit f58cfccc authored by beisir's avatar beisir

feat: 图片上传限制大小

parent 2ca85f31
import { Upload, Icon, Modal } from 'antd'; import { Upload, Icon, Modal, notification } from 'antd';
import React from 'react'; import React from 'react';
import { ReactSortable } from 'react-sortablejs'; import { ReactSortable } from 'react-sortablejs';
import { uploadImg } from '../../GoodsManage/service'; import { uploadImg } from '../../GoodsManage/service';
import styles from './styles.less'; import styles from './styles.less';
const ImageInfo = file => { const DETAIL_IMG_MAX_WIDTH = 750;
console.log(file); const LOOP_IMG_WIDTH_HEIGHT = 800;
const getBase64 = (img, callback) => {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
};
const ImageInfo = file =>
new Promise((resolve, reject) => {
console.log(file.size / 1024 / 1024);
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
notification.warning({
message: '上传图片不可以大于2MB',
});
reject();
}
getBase64(file, url => {
const image = new Image();
image.addEventListener('load', () => {
const { width } = image;
const { height } = image;
resolve({ width, height });
});
image.addEventListener('error', () => {
notification.warning({
message: '图片上传失败!',
});
reject();
});
image.src = url;
});
});
const isUploadNext = async ({ width, height }, id) => {
if (id === 'detailImageList') {
if (width > DETAIL_IMG_MAX_WIDTH) {
notification.warning({
message: `详情图宽度不可大于${DETAIL_IMG_MAX_WIDTH}`,
});
return false;
}
}
if (width > LOOP_IMG_WIDTH_HEIGHT || height > LOOP_IMG_WIDTH_HEIGHT) {
notification.warning({
message: `滑动图尺寸不可大于 ${LOOP_IMG_WIDTH_HEIGHT}*${LOOP_IMG_WIDTH_HEIGHT}`,
});
return false;
}
return true;
}; };
class PicturesWall extends React.Component { class PicturesWall extends React.Component {
state = { state = {
previewVisible: false, previewVisible: false,
...@@ -85,8 +137,14 @@ class PicturesWall extends React.Component { ...@@ -85,8 +137,14 @@ class PicturesWall extends React.Component {
const { max } = this.props; const { max } = this.props;
const that = this; const that = this;
const uploadProps = { const uploadProps = {
beforeUpload: file => { beforeUpload: async file => {
console.log(file); console.log(file);
const options = await ImageInfo(file);
console.log(options);
const isNext = await isUploadNext(options, that.props.id);
if (!isNext) {
return;
}
this.setState( this.setState(
state => ({ state => ({
newFile: [...state.newFile, file], newFile: [...state.newFile, file],
...@@ -111,6 +169,7 @@ class PicturesWall extends React.Component { ...@@ -111,6 +169,7 @@ class PicturesWall extends React.Component {
); );
}, },
); );
// eslint-disable-next-line consistent-return
return false; return false;
}, },
listType: 'picture-card', listType: 'picture-card',
......
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