Add.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { useState } from 'react';
  2. import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
  3. import { connect } from 'react-redux';
  4. import { Upload, message } from 'antd';
  5. import { backURL, gql } from '../../helpers';
  6. import { actionSetAvatar } from '../../actions';
  7. import { actionFullSetAvatar } from '../../redux/redux-thunk';
  8. const Add = ({ imageUrl, onUploadFile }) => {
  9. const [loading, setLoading] = useState(false)
  10. const [imageLoad, setImageLoad] = useState(false)
  11. const props = {
  12. name: 'photo',
  13. action: `${backURL}/upload`,
  14. headers: localStorage.authToken || sessionStorage.authToken ? { Authorization: 'Bearer ' + (localStorage.authToken||sessionStorage.authToken) } : {}
  15. }
  16. const handleChange = async ({ file }) => {
  17. if (file.status === 'uploading') {
  18. setLoading(true)
  19. }
  20. if (file.status === 'done') {
  21. message.success(`${file.name} file uploaded successfully`);
  22. await onUploadFile(file.response)
  23. console.log(file);
  24. setImageLoad(true)
  25. setLoading(false)
  26. } else if (file.status === 'error') {
  27. message.error(`${file.name} file upload failed.`);
  28. }
  29. }
  30. return (
  31. <Upload {...props}
  32. listType="picture-card"
  33. showUploadList={false}
  34. onChange={handleChange}
  35. className="avatar-uploader">
  36. {imageLoad ?
  37. <img src={`${backURL + '/' + imageUrl}`} alt="avatar" style={{ width: '100%' }} /> :
  38. <div>
  39. {loading ? <LoadingOutlined /> : <PlusOutlined />}
  40. <div style={{ marginTop: 8 }}>Upload</div>
  41. </div>}
  42. </Upload>
  43. )
  44. }
  45. export const CAdd = connect(state => ({ imageUrl: state?.myData?.avatar?.url}), { onUploadFile: actionFullSetAvatar })(Add)