【问题标题】:Firebase Storage: Invalid argument in `put` Expected Blob or FileFirebase 存储:“put”预期的 Blob 或文件中的参数无效
【发布时间】:2021-10-02 23:31:35
【问题描述】:

我正在学习教程并尝试使用网络摄像头作为 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

【问题讨论】:

    标签: javascript reactjs firebase firebase-storage


    【解决方案1】:

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

    来自documentation

    如果未指定 contentType 元数据且文件没有文件扩展名,则 Cloud Storage 默认为 application/octet-stream 类型。

    【讨论】:

    • 感谢您的回答,它确实通过了 firebase 存储,但它以 application/octet-stream 的形式运行,其中没有任何内容。
    • @NathanaelNeria 你所说的八位字节流是什么意思?你能分享一些截图来澄清一下吗?
    • @NathanaelNeria 您需要指定文件类型,检查更新的答案并尝试使用完全相同的代码。
    • 上传的文件类型是image/jpeg,但是上传的文件没有加载。截图如下:ibb.co/B3qXhRs
    • @NathanaelNeria 你能分享你最新代码的截图吗?
    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 2020-11-22
    • 2018-01-07
    • 2018-03-17
    • 2016-12-27
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多