MyDropzone.jsx 3.0 KB

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