我正在尝试将个人资料图片上传到前基存储,但它只是上传一个链接而不是整个图像

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

我有一个反应本机应用程序。现在我有一个屏幕,用户可以在其中从他或她的图库中选择图像。一旦他们选择了图像,我想拍摄该图像并将其存储在 Google Firebase 存储中。我已经研究这个问题一段时间了,刚刚意识到图像没有被上传,而只是一个正在上传的链接,这导致了几个问题。如何调整我的代码,以便推送整个图像而不是 Google Firebase Firestore 的链接?

这是我的 ProfilePicture.tsx 文件:

import React, {useContext, useState} from 'react';
import {Alert, Image, Text, TouchableOpacity, View} from 'react-native';
import * as ImagePicker from 'expo-image-picker';

import {useNavigation} from '@react-navigation/native';
import {UserContext} from '../../../Context/UserContext';

import {createUserWithEmailAndPassword} from 'firebase/auth';
import {auth, db, storage} from '../../../Utils/Firebase';
import {addDoc, collection} from 'firebase/firestore';
import {getDownloadURL, ref, updateMetadata, uploadBytes} from 'firebase/storage';

const ProfilePictureScreen = () => {
  const navigation = useNavigation();

  const userContext = useContext(UserContext);
  const {profilePicture, setProfilePicture} = userContext;
  const {
    profileEmail,
    setProfileEmail,
    profilePassword,
    setProfilePassword,
    profileFirstName,
    setProfileFirstName,
    profileLastName,
    setProfileLastName,
    profileUsername,
    setProfileUsername,
    profilePhone,
    setProfilePhone,
    profileLocation,
    setProfileLocation,
  } = userContext;

  const [hasPermission, setHasPermission] = useState<Boolean>(false);

  //...

  const uploadImage = (userId: string): void => {
    const imageRef = ref(storage, `ProfilePictures/${profilePicture.fileName}.jpeg`);
    const metadata = {
      contentType: 'image/jpeg',
    };
    uploadBytes(imageRef, profilePicture)

      /*

          image object example:
          {
            "assetId": "CC95F08C-88C3-4012-9D6D-64A413D254B3/L0/001",
            "base64": null,
            "duration": null,
            "exif": null,
            "fileName": "Omarjandali-profile-picture.jpeg",
            "fileSize": 13727225,
            "height": 3024,
            "type": "image",
            "uri": "file:///Users/omarjandali/Library/Developer/CoreSimulator/Devices/AB8866C8-D53D-47DA-99F2-5CD700EF4EE1/data/Containers/Data/Application/BC734A7E-06AB-4D6E-A078-AAE568879878/Library/Caches/ExponentExperienceData/%2540anonymous%252FIOweYou-6d1646a9-9f6c-418d-9753-3ce4dce5140a/ImagePicker/93CBFF4D-6F53-43D0-8B36-6652B937CB1E.jpg",
            "width": 4032
          }

      */

      .then(response => {
        console.log('Image was uploaded');
        return updateMetadata(imageRef, metadata);
      })
      .then(response => {
        console.log('Image was uploaded after metadata');
        getDownloadURL(imageRef)
          .then(url => {
            console.log(url);
            // createUserProfile(userId, url);
          })
          .catch(error => {
            console.error('Error getting download URL:', error);
          });
      })
      .catch(error => {
        console.error('Error uploading image:', error);
      });
  };

  const pickImage = () => {
    (async function () {
      const galleryStatus =
        await ImagePicker.requestMediaLibraryPermissionsAsync();
      setHasPermission(galleryStatus.status === 'granted');
    })();
  };

  const pickDirectImage = async () => {
    pickImage();
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [5, 5],
      quality: 1,
    });
    let selectedImage = result.assets[0];
    selectedImage.fileName = `${profileUsername}-profile-picture.jpeg`;

    // it is console logging the entire image objct from the expo-image-picker

    console.log(result.assets[0]);
    if (!result.canceled) {
      setProfilePicture(selectedImage);
    }
  };

  return (
    <View style={{flex: 1}}>
      <Text>Profile Picture Screen</Text>
      <TouchableOpacity onPress={() => pickDirectImage()}>
        <Text>Select Profile Picture</Text>
      </TouchableOpacity>
      {profilePicture ? (
        <Image
          style={{width: 100, height: 100, margin: 10}}
          source={{uri: profilePicture.uri}}
        />
      ) : null}
      <Text>{profilePicture.fileName}</Text>
      <View>
        <TouchableOpacity
          onPress={() => {
            createUserAccount();
          }}>
          <Text>Submit</Text>
        </TouchableOpacity>
      </View>
      <View>
        <TouchableOpacity
          onPress={() => {
            navigation.goBack();
          }}>
          <Text>Back</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default ProfilePictureScreen;

为什么图片没有上传以及如何解决这个问题...任何人都可以帮助我。

当图像上传到firebase存储时,它给我以下错误:

javascript reactjs firebase react-native firebase-storage
1个回答
0
投票

此代码对我有用,请尝试使用此代码

    export const uploadImage = (uri, id = '', name = '') =>
      new Promise(function (resolve, reject) {
        const filename = uri.substring(uri.lastIndexOf('/') + 1);
        const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;
    
        console.log('uploadUri',uploadUri);
        console.log('`${name}/${id}/${filename}`',`${name}/${id}/${filename}`);
    
        const task = storage().ref(`${name}/${id}/${filename}`).putFile(uploadUri);
        // set progress state
        task.on(
          'state_changed',
          snapshot => {
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            switch (snapshot.state) {
              case 'paused':
                break;
              case 'running':
                break;
            }
          },
          error => {
            // A full list of error codes is available at
            // https://firebase.google.com/docs/storage/web/handle-errors
            reject(error.code);
          },
          () => {
            storage()
              .ref(`${name}/${id}/${filename}`)
              .getDownloadURL()
              .then(downloadURL => {
                console.log('sdf dks');
                // resolve(downloadURL);
              });
    
            console.log('Upload completed!');
            // Upload completed successfully, now we can get the download URL
          },
        );
      });
© www.soinside.com 2019 - 2024. All rights reserved.