Skip to content

Instantly share code, notes, and snippets.

@esaramago
Created December 15, 2024 11:34
Show Gist options
  • Select an option

  • Save esaramago/9c7b0c5771d890b697cea8f9ac415d67 to your computer and use it in GitHub Desktop.

Select an option

Save esaramago/9c7b0c5771d890b697cea8f9ac415d67 to your computer and use it in GitHub Desktop.
Image to base64
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