UploadImage.jsx 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import React, { useState } from 'react';
  2. import { setProperty } from '@/utils/css';
  3. import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
  4. import Upload from './Upload';
  5. import styles from './style.less';
  6. function beforeUpload (file) {
  7. const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
  8. if (!isImage) {
  9. message.error('请上传 JPG , PNG或GIF 图片!');
  10. }
  11. const isLt10M = file.size / 1024 / 1024 < 10;
  12. if (!isLt10M) {
  13. message.error('图片大小必须小于 10MB!');
  14. }
  15. return isImage && isLt10M;
  16. }
  17. const UploadButton = (props) => (
  18. <div>
  19. {props.loading ? <LoadingOutlined /> : <PlusOutlined />}
  20. <div style={{ marginTop: 8 }}>上传</div>
  21. </div>
  22. );
  23. export default (props) => {
  24. const { value, onChange, width = 200, ratio = 1 } = props;
  25. const [loading, setLoading] = useState(false);
  26. const handleChange = info => {
  27. if (info.file.status === 'uploading') {
  28. setLoading(true);
  29. return;
  30. }
  31. if (info.file.status === 'error') {
  32. setLoading(false);
  33. return;
  34. }
  35. if (info.file.status === 'done') {
  36. setLoading(false);
  37. const { url, fileType } = info.file.response;
  38. // console.log('--------方--url-.>', url);
  39. onChange(url);
  40. }
  41. };
  42. const previewUrl = getRealPath ? getRealPath(value) : value;
  43. // console.log('--------previewUrl----->', previewUrl);
  44. React.useEffect(() => {
  45. setProperty('--cust-upload-ratio', ratio);
  46. }, [ratio]);
  47. React.useEffect(() => {
  48. setProperty('--cust-upload-width', `${width}px`);
  49. }, [width]);
  50. // console.log('-----里层----->value,', value);
  51. return (
  52. <Upload
  53. listType="picture-card"
  54. className={styles['ant-upload']}
  55. style={{ width: '200px' }}
  56. showUploadList={false}
  57. beforeUpload={beforeUpload}
  58. onChange={handleChange}
  59. >
  60. {value ? <img src={previewUrl} className="cust-img-thumb" alt="avatar" style={{ width: '100%', height: '100%' }} /> : <UploadButton loading={loading} />}
  61. </Upload>
  62. );
  63. }