Jukka Koivu
Jukka Koivu

Reputation: 319

How do I convert image file to base64?

I am want to save image as base64 to aws s3 bucket. There is a lambda that will decoder the base64.

These are my current states for the images. One is for selected file that is the image and the one is for the image that is seen as preview on the page.

 const [selectedFile, setSelectedFile] = useState('')
 const [preview, setPreview] = useState()

Then I have useEffect function for selecting the file and also sets the object URL as the preview image.

  useEffect(() => {
    if (!selectedFile) {
      setPreview(undefined)
      return
    }

    const objectURL = window.URL.createObjectURL(selectedFile)
    setPreview(objectURL)

    return () => window.URL.revokeObjectURL(objectURL)
  }, [selectedFile])

  const selectFile = (event) => {
    setSelectedFile(event.target.files[0])
  }

And this is the input component where the onChange function is called.

 <Input
   style={input}
   type='file'
   accept='.jpg, .png|image/*'
   id='image'
   name='Upload image'
   onChange={selectFile}
 />

Is there a better way to handle the base64 conversion?

Upvotes: 0

Views: 13972

Answers (1)

Jukka Koivu
Jukka Koivu

Reputation: 319

I managed to solve this by relatively short lines of code. I take the selectedFile from the state and then convert it to base64. I tested it with the separate button and I got base64 image in the console.


  const convertToBase64 = () => {
    const reader = new FileReader()

    reader.readAsDataURL(selectedFile)

    reader.onload = () => {
      console.log('called: ', reader)
      setBase64IMG(reader.result)
    }
  }

Upvotes: 6

Related Questions