【问题标题】:Upload files to firebase storage using react native expo使用 react native expo 将文件上传到 firebase 存储
【发布时间】:2021-11-30 17:56:08
【问题描述】:

我正在尝试使用 expo 将文件上传到 firebase 存储,但是当我尝试将文件上传到 firebase 存储时出现警告。

这是我用来从设备中选择文件的功能

const pickDocument = async () => {
    let result = await DocumentPicker.getDocumentAsync({
      // type: "application/pdf",
    });

    if (result != null) {
      setfile(result);
      setfileName(result.name);
      seturi(result.uri);
      console.log(result);
    }
  };

这是我用来上传文件的功能

  const uploadLessonSlide = async (uri) => {
    const blob = await new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.onload = function () {
        resolve(xhr.response);
      };
      xhr.onerror = function (e) {
        console.log("error");
        console.log(e);

        reject(new TypeError("Network request failed"));
      };
      xhr.responseType = "blob";
      xhr.open("GET", uri, true);
      xhr.send(null);
    });

    const ref = storage.ref().child("images");
    const snapshot = await ref.put(blob);

    blob.close();

    return await snapshot.ref.getDownloadURL();
  };

这是警告信息

[Unhandled promise rejection: TypeError: Network request failed]
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:600:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit

这是文件选择器的 console.log() 结果

Object {
  "name": "sinhala-nisadas-10.jpg",
  "size": 19346,
  "type": "success",
  "uri": "/data/user/0/host.exp.exponent/cache/ExperienceData/%40shehan82%2FschoolyMobNative/DocumentPicker/97a75d14-1b7f-468b-aeae-59a6e65aa96b.jpg",
}

我从 xhr.onerror 收到的错误消息

Event {
  "isTrusted": false,
}

【问题讨论】:

    标签: javascript firebase react-native expo firebase-storage


    【解决方案1】:

    您可以尝试将 xhr 调用替换为 fetch

      const pickDocument = async () => {
        let result = await DocumentPicker.getDocumentAsync({
          // type: "application/pdf",
        });
    
        if (result != null) {
          const r = await fetch(result.uri);
          const b = await r.blob();
          console.log(JSON.stringify(b));
          console.log(result);
        }
      };
    

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2020-03-06
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多