import React,{useState} from 'react';
import { Upload, Icon, message,Spin } from 'antd';
import serviceApi from '@/utils/api';
import {MessageTip} from '@/utils/tools.js'
import './upload.css'
// 上传单张图片
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
function 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('图片大小不能超过 2MB!');
}
return isJpgOrPng && isLt2M;
}
const UploadAvatar = (props) =>{
const [loading,setLoading] = useState(false)
const [imageUrl,setImageUrl] = useState('')
const handleChange = info => {
if (info.file.status === 'uploading') {
setLoading(true)
return;
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj, imageUrl =>{
setLoading(false)
if(info.file.response.success){
const {module} = info.file.response // 返回的图片地址
props.childImg(module) // 传给父级的
setImageUrl(imageUrl)
MessageTip('success','文件上传成功')
}
});
}
};
const uploadButton = (
<div>
{
loading?<Spin />:''
}
<div className="ant-upload-text">Upload</div>
</div>
);
return (
<Upload
name="file"
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action={serviceApi.uploadFile}
data={{type:1}} // type 1图片 2试卷
beforeUpload={beforeUpload}
onChange={handleChange}
>
{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
</Upload>
);
}
export default UploadAvatar;
antd 里面的Upload图片上传
猜你喜欢
转载自blog.csdn.net/Miss_liangrm/article/details/104324089
今日推荐
周排行