index.jsx 1.47 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
import { doFetch } from '@/utils/doFetch';
import { Avatar, message, Upload } from 'antd';

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const Header = ({ currentUser, run }) => {
  const imageUrl = currentUser?.head_url ?? null;

  const handleChange = (info) => {
    if (info.file.status === 'done') {
      doFetch({
        url: `/webtool/v1/user/${currentUser?.id}`,
        params: { head_url: info?.file?.response?.url ?? null },
        method: 'PUT',
      }).then((res) => {
        if (res?.code === 0) {
          run();
        }
      });
    }
  };

  const uploadButton = (
    <Avatar size={45} style={{ flexShrink: 0 }}>
      {currentUser?.user_name?.charAt(0)}
    </Avatar>
  );

  const token = localStorage.getItem('TOKENES');

  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={`${REACT_APP_URL}/webtool/upload`}
      headers={{
        Authorization: token,
      }}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? <Avatar size={45} style={{ flexShrink: 0 }} src={imageUrl} /> : uploadButton}
    </Upload>
  );
};
export default Header;