React Native 应用程序中的 Firebase 图像 URL 问题

问题描述 投票:0回答:1

我正在使用 Firebase 和 Expo 开发 React Native 应用程序,并且面临图像 URL 的问题。

我正在使用 Firebase Storage 来存储我的图像,并且我已经在我的应用程序中实现了图像上传功能。但是,当我尝试获取上传图像的 URL 时,它返回一个指向未定义图像的 URL,因此在我的应用程序中,除了它的“骨架”之外,我没有图像

我检查了 firebase 存储,为我的图像保存的 URL 也未定义。我希望这些 URL 指向上传的图像。

这是我正在选择并尝试上传并获取图像 URL 的代码片段:

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

if (!image.canceled) {
      setImage(image.assets[0].uri);
    }

const addPost = async (data) => {
if (image) {
const imageRef = ref(storage, `images/${auth.currentUser.uid}/${Date.now()}`;
image, {
         contentType: 'image/jpeg',
       });
)
const response = await uploadBytesResumable(imageRef, image);
const URLimage = await getDownloadURL(response.ref);
console.log("Image URL: ", URLimage);
// Here, URLimage is a URL, but it points to an undefined image
// Exemple of URL : https://firebasestorage.googleapis.com/v0/b/yowl-join.appspot.com/o/images%2FBQxDprUiJ7VL4j1CuMWxWukLM742%2F1706977884063?alt=media&token=[token]

// Saving the URL in Firestore
await addDoc(collection(db, "posts"), {
  userID: auth.currentUser.uid,
  post: post,
  likes: "",
  imageUri: URLimage,
  username: getUsername(),
  timestamp: serverTimestamp(),
});

//...

在我的应用程序中,当我从库中选择图像时,我会在 POST 之前将其显示在我的应用程序上,这样我就可以看到我的图像正确显示,因此问题是在我的 POST 之后。

Image in my app

这是我的 firebase 存储

Firebase storage

我无法在 firebase 中预览图像

我尝试直接在 Firebase 存储中导入图片,并将 URL 直接放入我的代码中,然后我的应用程序中会显示整个图像。

My image put direclty in firebase storage

我已经彻底审查了我的代码,检查了 Firebase 存储规则,并确保了正确的身份验证。
我认为问题出在

const response = await uploadBytesResumable(imageRef, image);

因为我的存储中的图像文件只有9个字节。它包含“未定义”
我尝试过仅使用“uploadBytyes”,但我有:ReferenceError:属性“uploadBytes”不存在。

有人以前遇到过这个问题并有解决方法的建议吗?

javascript react-native google-cloud-firestore react-native-firebase
1个回答
0
投票

我找到了解决方案,我需要将图像的 URI 转换为“blob”,然后再将其发送到 firebase

const pickImage = async () => {
    let image = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
// Some code 
if (image){
    const response = await fetch(image);
    const blob = await response.blob();
    const uploadTask = uploadBytesResumable(imageRef, blob); 
  

© www.soinside.com 2019 - 2024. All rights reserved.