MyDropzone.jsx 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import {useEffect, useState} from "react";
  2. import {useDropzone} from "react-dropzone";
  3. import {Box, Typography} from "@mui/material";
  4. export const MyDropzone = ({onLoad}) => {
  5. const [files, setFiles] = useState([]);
  6. const {getRootProps, getInputProps, isDragActive} = useDropzone({
  7. accept: 'image/*', onDrop: acceptedFiles => {
  8. setFiles(acceptedFiles.map(file => Object.assign(file, {
  9. preview: URL.createObjectURL(file)
  10. })));
  11. }})
  12. const thumbs = files.map(file => (
  13. <Box
  14. key={ file.name }
  15. style={{
  16. display: 'inline-flex',
  17. borderRadius: 2,
  18. border: '1px solid #eaeaea',
  19. marginBottom: 8,
  20. marginRight: 8,
  21. width: 500,
  22. height: 500,
  23. padding: 4,
  24. boxSizing: 'border-box'
  25. }}
  26. >
  27. <Box
  28. style={{
  29. display: 'flex',
  30. minWidth: 0,
  31. overflow: 'hidden'
  32. }}
  33. >
  34. <img
  35. src={file.preview}
  36. style={{
  37. display: 'block',
  38. width: 'auto',
  39. height: '100%',
  40. objectFit: 'cover',
  41. objectPosition: 'center center'
  42. }}
  43. alt={file.name}
  44. />
  45. </Box>
  46. </Box>
  47. ));
  48. useEffect(() => {
  49. files.forEach(file => URL.revokeObjectURL(file.preview));
  50. onLoad(files)
  51. }, [files]);
  52. return (
  53. <section
  54. style={{
  55. display: 'flex',
  56. flexDirection: 'column',
  57. justifyContent: 'space-between',
  58. alignItems: 'center',
  59. width:"100%",
  60. borderRadius: '20px',
  61. padding: '20px'
  62. }}
  63. >
  64. <Box
  65. style={{
  66. width:"100%",
  67. height: "100%",
  68. border: '1px dashed #616161',
  69. borderRadius: '20px',
  70. padding: '20px'
  71. }}
  72. {...getRootProps()}
  73. >
  74. <input {...getInputProps()} />
  75. {isDragActive ?
  76. <Typography
  77. variant='body1'
  78. color='#616161'
  79. >
  80. Drop the file here ...
  81. </Typography>
  82. :
  83. <Typography
  84. variant='body1'
  85. color='#616161'
  86. >
  87. Drag 'n' drop image files here, or click to select file
  88. </Typography>
  89. }
  90. <aside>
  91. {thumbs}
  92. </aside>
  93. </Box>
  94. </section>
  95. )
  96. }