将视频上传到ReactNative中的Firebase

时间:2019-06-28 19:41:59

标签: firebase react-native

如何通过React本机应用程序将视频上​​传到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,
}

2 个答案:

答案 0 :(得分:0)

如果要从Firebase存储和检索文件,则可以使用Firebase云存储。

https://firebase.google.com/docs/storage

答案 1 :(得分:0)

错误消息中有一个提示,说明您的问题是什么-Firebase存储期望文件或Blob,但您给它一个字符串。

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

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

videoRef.put(videoBlob)

希望这会有所帮助