使用React Native Expo上传文件到Firebase存储

4

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

这是File picker的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,
}

This is the function I use for upload files

This is the function I use to choose files from the device.

This is the Console.log() of the File picker result and the Warning


你能找到解决方案吗?我也在苦苦寻找同样的问题的解决方法,但是找不到。 - 4aLifeTime
1个回答

0

你可以尝试用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);
    }
  };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接