106 lines
2.7 KiB
JavaScript
106 lines
2.7 KiB
JavaScript
import React ,{useEffect, useRef, useState} from 'react';
|
||
import './Index.scss';
|
||
import { Modal , message } from 'antd';
|
||
import Cropper from 'react-cropper';
|
||
import 'cropperjs/dist/cropper.css';
|
||
import axios from 'axios';
|
||
|
||
function Index({onCancel,avatarImg,login}){
|
||
console.log('avatarImg,login', avatarImg,login);
|
||
|
||
const [ avatarPhoto , setAvatarPhoto ] = useState(avatarImg);
|
||
|
||
useEffect(()=>{
|
||
if(avatarImg){
|
||
setAvatarPhoto(avatarImg);
|
||
}
|
||
},[avatarImg])
|
||
|
||
const cropper = useRef();
|
||
|
||
const saveAvatar = async () => {
|
||
const imgUrl = cropper.current.cropper.getCroppedCanvas().toDataURL("image/png");
|
||
if (!imgUrl) {
|
||
message.info('请先上传图片');
|
||
}
|
||
const url = `/users/${login}/update_image.json`;
|
||
axios.put(url,{
|
||
image:imgUrl
|
||
}).then(result=>{
|
||
if(result){
|
||
message.success("头像修改成功!");
|
||
onCancel(true);
|
||
}
|
||
}).catch(error=>{})
|
||
}
|
||
|
||
function onChange(e){
|
||
|
||
let files;
|
||
if (e.dataTransfer) {
|
||
files = e.dataTransfer.files;
|
||
} else if (e.target) {
|
||
files = e.target.files;
|
||
}
|
||
|
||
if (!files || (files && files.length===0)) {
|
||
return;
|
||
}
|
||
const file = files[0];
|
||
if (!/^image\/\w+/.test(file.type)) {
|
||
message.info('请选择一个图片格式的文件');
|
||
return;
|
||
}
|
||
|
||
if (file.size > 2 * 1024 * 1024) {
|
||
message.info('仅支持文件大小小于2M的文件');
|
||
return;
|
||
}
|
||
|
||
const reader = new FileReader();
|
||
reader.onload = () => {
|
||
if(reader.result){
|
||
setAvatarPhoto(reader.result);
|
||
}
|
||
};
|
||
reader.readAsDataURL(files[0]);
|
||
}
|
||
|
||
return(
|
||
<Modal
|
||
visible={true}
|
||
width="638px"
|
||
footer={null}
|
||
centered
|
||
maskClosable={false}
|
||
title="修改头像"
|
||
onCancel={()=>onCancel(false)}
|
||
className="avatarBox"
|
||
>
|
||
<div className="avatarDiv">
|
||
<div>
|
||
<Cropper
|
||
style={{ height: 320, width: 320 }}
|
||
src={avatarPhoto}
|
||
guides={false}
|
||
preview="#updateAvatarImg"
|
||
ref={cropper}
|
||
aspectRatio={1}
|
||
/>
|
||
{/* <span className={"tips"}>仅支持JPG、GIF、PNG,且文件小于2M</span> */}
|
||
</div>
|
||
<div className="previewBox">
|
||
<div className={"previewImg"} id="updateAvatarImg"></div>
|
||
<div className="uploadBtn">
|
||
<label className={"uploadButton"} id="uploadBtn" htmlFor="inputImage">
|
||
<input type="file" className="sr-only" id="inputImage" name="file" accept="image/*" style={{ display: "none" }} onChange={onChange}></input>
|
||
点击上传
|
||
</label>
|
||
<a onClick={saveAvatar}>保存头像</a>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</Modal>
|
||
)
|
||
}
|
||
export default Index; |