组件使用代码:
<Upload
action="http://api.hnzhiu.com/api/v1/uploads"//必须写,不然上传图片时的状态不会有done
listType="picture-card"
showUploadList={false}
beforeUpload={this.beforeUpload}//上传图片时的校验:格式、大小
onChange={this.handleImgChange}//图片上传状态改变时的回调函数:uploading、done、error
>
{imageWapUrl ? <img src={imageWapUrl} alt="avatar" style={
{ width: '100%' }} /> : uploadButton}
</Upload>
相关函数:
//限制用户上传的图片格式和大小
beforeUpload=(file)=>{
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('仅支持上传 jpg / png 图片!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小限制 1024*1024 ,2M以下!');
}
return isJpgOrPng && isLt2M;
}
handleImgChange = (info) => {
console.log("图片上传开始");
console.log(info);
if (info.file.status === 'done') {//图片上传的状态判断一定要有,不然会上传多次
const xhr = new XMLHttpRequest;
const fd = new FormData();
fd.append('image', info.file.origi