Firebase Storage: Invalid argument in `put` Expected Blob or File

Viewed 87

I'm following a tutorial and tried to capture an image using webcam as a jpeg and I want to upload it to firebase storage where it requires me to upload it as file or blob. I'm able to upload an image when I use <input type = 'file'> format, but I want to upload an image directly from the webcam capture. Is there anyway to convert jpeg to file or blob?

Here's the code

import React, { useState } from 'react'
import Webcam from 'react-webcam'
import firebase from 'firebase'

const WebcamComponent = () => <Webcam/>

const videoConstraints = {
  width: 220,
  height: 200,
  facingMode: 'user'
}

const WebcamCapture = () => {
  const webcamRef = React.useRef(null)

  const [image, setImage] = useState('')

  const capture = React.useCallback(
    () => {
      const imageSrc = webcamRef.current.getScreenshot()

      setImage(imageSrc)

      const file = image
      var storage = firebase.storage()
      storage.ref('FormPhotos/' + file.name).put(file).on('state_changed', alert('success'), alert)
      console.log(image)
    },
    [webcamRef]
  )

  return (
    <div className = 'webcam-container'>
      <div className = 'webcam-img'>
        {
          image == '' ? <Webcam
            audio = {false}
            height = {200}
            ref = {webcamRef}
            screenshotFormat = 'image/jpeg'
            width = {220}
            videoConstraints = {videoConstraints}
          /> : <img src = {image}/>}
      </div>
      <div>
        {
          image != ''

            ? <button onClick = {(e) => {
              e.preventDefault()
              setImage('')
            }} className = 'webcam-btn'>
            Retake Image
            </button>
            : <button onClick = {(e) => {
              e.preventDefault()
              capture()
            }}>Capture</button>
        }
      </div>
    </div>
  )
}

export default WebcamCapture
1 Answers

The getScreenshot() method returns a base64 encoded string of the current webcam image. Use putString method instead of put and pass that imageSrc in it:

const imageSrc = webcamRef.current.getScreenshot()
const base64String = imageSrc.split(',')[1]
var storage = firebase.storage()
storage
  .ref('FormPhotos/' + file.name)
  .putString(base64string, "base64", {contentType: 'image/jpeg'})
  .then(() => {
    console.log("Image uploaded")
  }).catch((e) => console.log(e))

From the documentation,

If no contentType metadata is specified and the file doesn't have a file extension, Cloud Storage defaults to the type application/octet-stream.

Related