firebase存储:预期的blob或文件中的'put'参数无效

4ioopgfo  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(249)

我正在学习一个教程,并尝试使用网络摄像头将图像作为jpeg格式捕获,我想将其上载到firebase存储,在firebase存储中需要我将其作为文件或blob进行上载。我可以在使用时上传图像 <input type = 'file'> 格式,但我想直接从网络摄像头捕获上传图像。是否仍有将jpeg转换为文件或blob的方法?
这是密码

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
ecr0jaav

ecr0jaav1#

这个 getScreenshot() 方法返回当前网络摄像头图像的base64编码字符串。使用 putString 方法代替 put 把那个传过去 imageSrc 其中:

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))

根据文件,
如果未指定contenttype元数据且文件没有文件扩展名,则云存储默认为application/octet stream类型。

相关问题