繁体   English   中英

使用 expo react-native 将图像上传到 firebase

[英]Uploading image to firebase using expo react-native

我正在开发一个应用程序,我正在使用 expo,我想确保每个用户都可以将图像上传到 firebase,然后在个人资料页面上发布此图像。

使用 expo 这是我上传图像的方式:

const pickImage = async () => {
    let pickerResult = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(pickerResult);
    handleImagePicked(pickerResult);
  };

控制台中的结果是:

Object {
  "cancelled": false,
  "height": 312,
  "type": "image",
  "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fallergyn-app-77bfd368-65fd-43f9-8c34-9c35cef42c25/ImagePicker/daaa229c-c352-4994-ae18-ca2dbb3534ce.jpg",
  "width": 416,
}

这就是我上传到 firebase 的方式:

const handleImagePicked = async (pickerResult) => {
    try {
      if (!pickerResult.cancelled) {
        setImage(pickerResult.uri);
        await uploadImageAsync(pickerResult.uri);
        console.log("done");
      }
    } catch (e) {
      console.log(e);
      alert("Upload failed, sorry :(");
    } finally {
    }
  };

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

    const ref = firebase
      .storage()
      .ref()
      .child("images" + Math.random());

    const snapshot = await ref.put(blob);

    // We're done with the blob, close and release it
    blob.close();
    return await snapshot.ref.getDownloadURL();
  }

此代码有效,它保存图像的路径: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fallergyn-app-77bfd368-65fd-43f9-8c34-9c35cef42c25/ImagePicker/daaa229c-c352-4994-ae18-ca2dbb3534ce.jpg"在用户集合下的firebase中使用用户的uid。

我不确定这是否好,因为我想确保图像本身上传到 firebase,我在 StackOverflow 中看到一些关于这个问题的线程太旧或没有答案,所以我希望得到某种解决方案我需要做什么。

如果我使用

const ref = firebase
  .storage()
  .ref()
  .child("images" + Math.random());
  .putFile(uri);

这告诉我putFile is not a function. put(uri)相同

试试这个。 这个 function 从 firebase 返回保存图像的路径,您将存储在用户的文档中。

const handleImagePicked = async (pickerResult) => {
      if (!pickerResult.cancelled) {
        setImage(pickerResult.uri);
        const result = await uploadImageAsync(pickerResult.uri);
        if(result) {
           console.log('success');
           //save the result path to firestore user document
           return;
        }
        alert("Upload failed, sorry :(");
      }
  };
export const uploadImageAsync = async (uri: string) => {
  let filename = uri;
  if (Platform.OS === 'ios') {
    filename = uri.replace('file:', '');
  }

  const ext = filename.split('.').pop();
  const path = `images/${id}.${ext}`;
  const ref = firebase.storage().ref(path);

  try {
    const response = await fetch(filename);
    const blob = await response.blob();
    await ref.put(blob);
    return path;
  } catch {
    return null;
  }
};

暂无
暂无

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

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