Created
December 15, 2024 11:34
-
-
Save esaramago/9c7b0c5771d890b697cea8f9ac415d67 to your computer and use it in GitHub Desktop.
Image to base64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type MaxFileSize = number // in KB | |
| export default (file: File, maxFileSize?: MaxFileSize) => { | |
| let base64 = '' | |
| if (!file) return base64 | |
| const sizeInKb = file.size / 1024 | |
| const notTooBig = !maxFileSize || sizeInKb <= maxFileSize | |
| if (notTooBig) { | |
| const reader = new FileReader() | |
| reader.readAsDataURL(file) | |
| reader.onload = () => { | |
| base64 = reader.result as string | |
| } | |
| } else { | |
| alert('Imagem muito grande. Máximo 200kb') | |
| } | |
| return base64 | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment