繁体   English   中英

Firebase 存储:`put` 预期 Blob 或文件中的参数无效

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

我正在学习教程并尝试使用网络摄像头作为 jpeg 捕获图像,我想将其上传到 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

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 元数据且文件没有文件扩展名,则 Cloud Storage 默认为类型 application/octet-stream。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM