【问题标题】:How does one upload an m4a audio file to Firebase Storage using react-native and expo?如何使用 react-native 和 expo 将 m4a 音频文件上传到 Firebase 存储?
【发布时间】:2019-10-11 18:06:30
【问题描述】:

我正在使用 react-native 和 expo 构建一个应用程序。该应用程序的一项功能允许用户录制音频,然后将其上传到 Firebase 存储。我设法成功录制了音频,还设法将缓存文件作为 blob 检索,但是当尝试将其上传到 Firebase 存储时,它失败并出现错误代码 400,“错误请求。无法创建对象”。让我感到困惑的是,我使用相同的过程来上传完美的图片。为什么音频文件会失败?

我成功地录制了音频,并使用 XMLHttpRequest 检索了缓存文件(作为 blob)。当我将它记录到控制台时输出的结果 blob 如下所示:

    Blob {
        "_data": Object {
            "blobId": "lengthy blob id",
            "name": "recording-XXXXXX.m4a",
            "offset": 0,
            "size": 371097,
            "type": "audio/x-m4a",
        },
    }

当我尝试使用 ref.put(blob) 上传到 Firebase 存储时,它返回 400 错误:“错误请求。无法创建对象”。我还尝试将 contentType 作为元数据的一部分提供,看看这是否会有所作为,但无济于事。

这就是我获取文件的方式:

    const blob = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = () => {
            resolve(xhr.response);
        };
        xhr.onerror = (e) => {
            reject(new TypeError('Network request failed'));
        };
        xhr.responseType = 'blob';
        xhr.open('GET', uri, true);
        xhr.send(null);
    });

要将 blob 上传到 Firebase 存储,我执行以下操作:

    const clientuid = 123;
    const siteid = 'ABC';
    const audioName = `${Date.now}.m4a`;
    this.setState({ uploading: true });
    const ref = firebase.storage().ref().child(`audio/${clientuid}/${siteid}/${audioName}`);
    ref.put(blob)
    .then(async (snapshot) => {
        const fullUrl = await snapshot.ref.getDownloadURL();
        // Upload the Url to Firebase realtime database...
        Alert.alert('Upload Successful');
    .catch((error) => {
        console.log(error.serverResponse);
        Alert.alert('Failed to create object!');
    })
    .finally(() => {
        blob.close()
        this.setState({ uploading: false });
    });

上传失败并出现以下错误。serverResponse:

    {
       "error": {
          "code": 400,
          "message": "Bad Request. Could not create object",
          "status": "CREATE_OBJECT"
       }
    }

【问题讨论】:

    标签: react-native firebase-storage expo


    【解决方案1】:

    在您的情况下,我认为您也可以通过使用文件路径获取文件来创建 blob。

    let res = await fetch(filePath);
    let blob = await res.blob
    

    在我的情况下,这总是有效的。

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 1970-01-01
      • 2018-06-21
      • 2020-09-08
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多