Last active
July 13, 2022 09:31
-
-
Save safronman/850f2236815280a849311e1a9384d5ec to your computer and use it in GitHub Desktop.
Conver file to base64 and upload
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
| const uploadHandler = (e: ChangeEvent<HTMLInputElement>) => { | |
| if (e.target.files && e.target.files.length) { | |
| const file = e.target.files[0] | |
| if (file.size < 4000000) { | |
| convertFileToBase64(file, (file64: string) => { | |
| dispatch(updateProfileTC({avatar: file64})) | |
| }) | |
| } else { | |
| dispatch(setAppErrorAC('Файл слишком большого размера')) | |
| } | |
| } | |
| } | |
| // https://stackoverflow.com/a/20285053 js | |
| // https://stackoverflow.com/a/47177899 react | |
| const convertFileToBase64 = (file: File, callBack: (value: string) => void) => { | |
| // https://developer.mozilla.org/ru/docs/Web/API/FileReader/FileReader | |
| const reader = new FileReader(); | |
| // https://developer.mozilla.org/ru/docs/Web/API/FileReader/readAsDataURL | |
| reader.onloadend = () => { | |
| const file64 = reader.result as string | |
| callBack(file64) | |
| } | |
| reader.readAsDataURL(file) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment