// 如何获取图片宽高, 以及图片大小校验, 这里用的是Antd上传组件的自定义上传方法
<Upload customRequest={this.originUpload} beforeUpload={this.handleBeforeUpload}>
上传
</Upload>
1. 使用组件获取宽高
originUpload = async options => {
let me = this;
return new Promise(function (resolve, reject) {
const fileReader = new FileReader();
fileReader.onload = e => {
const src = e.target.result;
const image = new Image();
image.onload = async function () {
// 这里this.width和this.height是图片的宽高px
console.log(this.width);
console.log(this.height);
// 在这里开始调后端接口
}
image.onerror = reject;
image.src = src;
}
fileReader.readAsDataURL(options.file);
})
}
2. 使用地址获取宽高
const {width, heigth} = await this.handleGetImageSize(url);
handleGetImageSize = (url) => {
return new Promise(function (resolve, reject) {
const image = new Image();
image.onload = () => {
resolve({width: image.width, height: image.height});
};
image.onerror = () => {
reject(new Error('error'));
}
image.src = url;
});
}
// 图片大小校验
handleBeforeUpload = file => {
// 支持格式:jpg jpeg png
const isFormat = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';
if (!isFormat) {
// 写错误提示语
noticeStore.setLastError({effect: 1, tip: '请上传 JPG/JPEG/PNG 格式图片!'});
return false;
}
const isLimit = file.size / 1024 / 1024 < 10; // 单位M
if (!isLimit) {
// 写错误提示语
noticeStore.setLastError({effect: 1, tip: '请上传 10MB 以内的图片!'});
return false;
}
return true;
}
// 一次性最多只能上传20个文件以及相关校验
import React from 'react';
import { Upload, message } from 'antd';
const App = () => {
const handleBeforeUpload = (file, fileList) => {
if (fileList.length > 20) {
message.error('一次性最多只能上传20个文件');
return false; // 阻止上传
}
return true; // 允许上传
};
const handleUpload = (fileList) => {
console.log(fileList);
};
return (
<Upload beforeUpload={handleBeforeUpload} onChange={handleUpload}>
<button>Select Files</button>
</Upload>
);
};
export default App;
// 格式大小等校验
const handleBeforeUpload = (file, fileList) => {
if (fileList && fileList.length > 20) {
noticeStore.lastNoticeMessage({code: 1, message: '每次只能上传20个,请重新选择'});
return false;
}
const isLt = file.size / 1024 / 1024 < 30;
console.log(file.size / 1024 / 1024, '大小');
if (!isLt) {
noticeStore.lastNoticeMessage({code: 1, message: '不能超过30M'});
return false;
}
const isJpgOrPng =
file.type === 'image/jpg' ||
file.type === 'image/jpeg' ||
file.type === 'image/png' ||
file.type === 'image/bmp' ||
file.type === 'image/gif' ||
file.type === 'image/svg' ||
file.type === 'image/webp';
if (!isJpgOrPng) {
noticeStore.lastNoticeMessage({code: 1, message: '图片格式不正确'});
return false;
}
return true;
};