Uploader.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { Theme } from '@mui/material';
  2. import { FC, useContext, useRef } from 'react';
  3. import { rootContext } from '@/context';
  4. import CustomButton from '../customButton/CustomButton';
  5. import { FILE_MIME_TYPE } from '@/consts';
  6. import { makeStyles } from '@mui/styles';
  7. import type { UploaderProps } from './Types';
  8. const getStyles = makeStyles((theme: Theme) => ({
  9. btn: {},
  10. }));
  11. const Uploader: FC<UploaderProps> = ({
  12. label,
  13. accept,
  14. btnClass = '',
  15. disabled = false,
  16. disableTooltip = '',
  17. maxSize,
  18. overSizeWarning = '',
  19. handleUploadedData,
  20. handleUploadFileChange,
  21. handleUploadError,
  22. setFileName,
  23. }) => {
  24. const inputRef = useRef(null);
  25. const type = useRef<FILE_MIME_TYPE>(FILE_MIME_TYPE.CSV);
  26. const classes = getStyles();
  27. const { openSnackBar } = useContext(rootContext);
  28. const handleUpload = () => {
  29. const uploader = inputRef.current! as HTMLFormElement;
  30. const reader = new FileReader();
  31. // handle uploaded data
  32. reader.onload = async e => {
  33. const data = reader.result;
  34. if (data) {
  35. handleUploadedData(data as string, inputRef.current!, type.current);
  36. }
  37. };
  38. // handle upload error
  39. reader.onerror = e => {
  40. if (handleUploadError) {
  41. handleUploadError();
  42. }
  43. console.error(e);
  44. };
  45. uploader!.onchange = (e: Event) => {
  46. const target = e.target as HTMLInputElement;
  47. const file: File = (target.files as FileList)[0];
  48. if (file) {
  49. type.current = file.type as FILE_MIME_TYPE; // This will log the MIME type of the file
  50. }
  51. const isSizeOverLimit = file && maxSize && maxSize < file.size;
  52. if (!file) {
  53. return;
  54. }
  55. if (isSizeOverLimit) {
  56. openSnackBar(overSizeWarning, 'error');
  57. const uploader = inputRef.current! as HTMLFormElement;
  58. uploader.value = null;
  59. return;
  60. }
  61. setFileName(file.name || 'file');
  62. handleUploadFileChange && handleUploadFileChange(file, inputRef.current!);
  63. reader.readAsText(file, 'utf8');
  64. };
  65. uploader.click();
  66. };
  67. return (
  68. <section>
  69. <CustomButton
  70. variant="contained"
  71. className={`${classes.btn} ${btnClass}`}
  72. onClick={handleUpload}
  73. disabled={disabled}
  74. tooltip={disabled ? disableTooltip : ''}
  75. >
  76. {label}
  77. </CustomButton>
  78. <input
  79. ref={inputRef}
  80. id="fileId"
  81. type="file"
  82. accept={accept}
  83. style={{ display: 'none' }}
  84. />
  85. </section>
  86. );
  87. };
  88. export default Uploader;