简体   繁体   中英

Upload files to firebase storage using react native expo

I am trying to upload files to the firebase storage using expo, but there is a warning when I try to upload files to firebase storage.

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

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

This is the function I use for upload files

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

This is the Warning message

[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

This is the console.log() result of File picker

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",
}

Error message I got from xhr.onerror

Event {
  "isTrusted": false,
}

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

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

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

you can try replacing the xhr call with 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);
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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