首页 > 解决方案 > 在 ReactNative 中将视频上传到 Firebase

问题描述

如何通过反应原生应用程序将视频上​​传到 Firebase?我已经成功实现了功能:从 Firebase 云存储上传和下载图像。但是我想上传视频。有什么指导吗?

我能够获得视频的 URI。以下是我用来将视频上传到 Firebase 的功能。

uploadVideo(uri) {
      console.log("inside");

        const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri

        const videoRef = firebase.storage().ref('images').child(`${Student.FirstName}`).child('video_098')
        var metadata = {
          contentType: 'video/mp4'
        };
        var uploadTask = videoRef.put(uploadUri, metadata);

        // Listen for state changes, errors, and completion of the upload.
        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
          function(snapshot) {
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
              case firebase.storage.TaskState.PAUSED: // or 'paused'
                console.log('Upload is paused');
                break;
              case firebase.storage.TaskState.RUNNING: // or 'running'
                console.log('Upload is running');
                break;
            }
          }, function(error) {

          // A full list of error codes is available at
          // https://firebase.google.com/docs/storage/web/handle-errors
          switch (error.code) {
            case 'storage/unauthorized':
              // User doesn't have permission to access the object
              break;

            case 'storage/canceled':
              // User canceled the upload
              break;

            case 'storage/unknown':
              // Unknown error occurred, inspect error.serverResponse
              break;
          }
        }, function() {
          // Upload completed successfully, now we can get the download URL
          uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
            console.log('File available at', downloadURL);
          });
        });


  }

这给了我以下错误:

YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
FirebaseStorageError {
  "code_": "storage/invalid-argument",
  "message_": "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.",
  "name_": "FirebaseError",
  "serverResponse_": null,
}

标签: firebasereact-native

解决方案


错误消息中有一个提示,你的问题是什么 - firebase 存储需要一个文件或 blob,但你给它一个字符串。

如果您使用的是 RN 版本 > 0.54,则需要先使用 URI 获取 blob,然后再获取put,因此如下所示:

const fetchedVideo = await fetch(uploadUri);
const videoBlob = await response.blob();

videoRef.put(videoBlob)

希望这可以帮助


推荐阅读