forked from Gitlink/forgeplus-react
71 lines
2.2 KiB
JavaScript
71 lines
2.2 KiB
JavaScript
import React, { useEffect, useState } from 'react';
|
|
import { Upload , Icon , message } from "antd";
|
|
import { getUploadActionUrl } from 'educoder';
|
|
import cookie from 'react-cookies';
|
|
|
|
const TokenKey = 'autologin_trustie';
|
|
|
|
function UploadImage({ getImage , url, getImageId, maxSize = 2, action = getUploadActionUrl(), getImageUrl }){
|
|
const [ imageUrl , setImageUrl ] = useState(undefined);
|
|
const [loading, setLoading] = useState(false);
|
|
useEffect(()=>{
|
|
setImageUrl(url);
|
|
},[url])
|
|
|
|
function getBase64(img, callback) {
|
|
const reader = new FileReader();
|
|
reader.addEventListener('load', () => callback(reader.result));
|
|
reader.readAsDataURL(img);
|
|
reader.onload = function(e) {
|
|
getImage && getImage(e.target.result); // 上传的图片的编码
|
|
}
|
|
}
|
|
// 上传前
|
|
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 < maxSize;
|
|
if (!isLt2M) {
|
|
message.error(`上传的图片不能超过${maxSize}MB!`);
|
|
}
|
|
return isJpgOrPng && isLt2M;
|
|
}
|
|
// 上传完成后
|
|
function handleChange(info){
|
|
setLoading(true);
|
|
if(info && info.file && info.file.status === "done"){
|
|
setLoading(false);
|
|
getImageId && getImageId(info.file.response.id);
|
|
getImageUrl && getImageUrl(info.file.response.url)
|
|
getBase64(info.file.originFileObj, imageUrl =>
|
|
setImageUrl(imageUrl)
|
|
);
|
|
}
|
|
}
|
|
return(
|
|
<Upload
|
|
name="file"
|
|
listType="picture-card"
|
|
className="avatar-uploader"
|
|
showUploadList={false}
|
|
action={action}
|
|
beforeUpload={beforeUpload}
|
|
onChange={handleChange}
|
|
accept=".png,.jpg,.jpeg"
|
|
withCredentials={ true }
|
|
headers={{ Authorization: cookie.load(TokenKey) }}>
|
|
{
|
|
imageUrl ?
|
|
<img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
|
|
:
|
|
<div>
|
|
<Icon type={loading ? 'loading' : 'plus'} />
|
|
<div className="ant-upload-text">点击上传</div>
|
|
</div>
|
|
}
|
|
</Upload>
|
|
)
|
|
}
|
|
export default UploadImage; |