Uploader.tsx 2.2 KB

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