UploadImage.jsx 2.1KB

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