UploadImage.jsx 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import React, { useState } from 'react';
  2. import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
  3. import Upload from './Upload';
  4. function beforeUpload(file) {
  5. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'||file.type==='image/gif';
  6. if (!isJpgOrPng) {
  7. message.error('请上传 JPG , PNG或GIF 图片!');
  8. }
  9. const isLt10M = file.size / 1024 / 1024 < 10;
  10. if (!isLt10M) {
  11. message.error('图片大小必须小于 10MB!');
  12. }
  13. return isJpgOrPng && isLt10M;
  14. }
  15. const UploadButton = (props) => (
  16. <div>
  17. {props.loading ? <LoadingOutlined /> : <PlusOutlined />}
  18. <div style={{ marginTop: 8 }}>上传</div>
  19. </div>
  20. );
  21. export default (props) => {
  22. const { value, onChange } = props;
  23. const [loading, setLoading] = useState(false);
  24. const handleChange = info => {
  25. if (info.file.status === 'uploading') {
  26. setLoading(true);
  27. return;
  28. }
  29. if (info.file.status === 'error') {
  30. setLoading(false);
  31. return;
  32. }
  33. if (info.file.status === 'done') {
  34. setLoading(false);
  35. onChange(info.file.response);
  36. }
  37. };
  38. return (
  39. <Upload
  40. listType="picture-card"
  41. className="image-uploader"
  42. showUploadList={false}
  43. beforeUpload={beforeUpload}
  44. onChange={handleChange}
  45. >
  46. {value ? <img src={value} alt="avatar" style={{ width: '100%', height: '100%' }} /> : <UploadButton loading={loading} />}
  47. </Upload>
  48. );
  49. }