Skip to content

Instantly share code, notes, and snippets.

@safronman
Last active July 13, 2022 09:31
Show Gist options
  • Select an option

  • Save safronman/850f2236815280a849311e1a9384d5ec to your computer and use it in GitHub Desktop.

Select an option

Save safronman/850f2236815280a849311e1a9384d5ec to your computer and use it in GitHub Desktop.
Conver file to base64 and upload
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