繁体   English   中英

使用 react native expo 将文件上传到 firebase 存储

[英]Upload files to firebase storage using react native expo

我正在尝试使用 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,
}

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

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

这是文件选择器结果的 Console.log() 和警告

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM