简体   繁体   中英

How to upload image to firebase in expo react native

I used RNFirebase before to upload image to firebase. At that time, I used this code :

firebase
        .storage()
              .ref()
              .child(`posts/${fileName}`)
              .putFile(postImage.uri)
              .then((value) => {
                console.log('Put file response :', value);

In here,

let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      // allowsEditing: true,
      // aspect: [4, 3],
      quality: 1
    });

    console.log(result);

    if (!result.cancelled) {
      this.setState({ imageData: result });
    }



postImage  = result.uri

That is postImage is the url of image. However, I have to change the code using firebase and have to upload image to firebase storage and database. So I used this code :

firebase
        .storage()
              .ref()
              .child(`posts/${fileName}`)
              .put(postImage.uri)
              .then((value) => {
                console.log('Put file response :', value);

But the result has the errors on the screen. It returns [object object] on the screen. 在此处输入图片说明 So I looked on the docs of firebase and the function put must have the data like this : put(data | blob) But I can't understand this. How can do I this? Let me know how to fix it~ Thanks and best wishes.

Here is the code snippet i have used to store You need to check the ImagePicker code ie path of the file in expo it is used in bare react-native app


  const [progress, setProgress] = useState(0);
  const [uploading, setUploading] = useState(false);

  const storageForDefaultApp = storage();

  const uploadImage = async image => {
    setUploading(true);
    setProgress(0);
    // console.log('image', image);
    const task = storageForDefaultApp.ref(image.ref).putFile(image.path);

    task.on('state_changed', snap => {
      setProgress(Math.round(snap.bytesTransferred / snap.totalBytes) * 10000);
    });

    try {
      const final = await task;
      console.log('final image', final);
    } catch (e) {
      console.error(e);
    }
    setUploading(false);
  };

  const _openPicker = () => {
    ImagePicker.openPicker({
      cropping: false,
      multiple: false,
      compressImageQuality: 0.8,
      mediaType: 'photo',
    }).then(image => {
      let timestamp = moment().format(TIMESTAMP_FORMAT);
      const final = {...image, id: timestamp, ref: timestamp + '.jpeg'};
      setFiles([...files, final]);
      uploadImage(final);
    });
  };

I have done this way hope it would help

  const pickImage = async () => {
    getPermission();
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    if (!result.cancelled) {
      setImage(result.uri);
      setUploading(true);
    }
  };

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

  // here I am uploading the image to firebase storage
  const uploadImageToBucket = async () => {
    let blob;
    try {
      setUploading(true);
      blob = await getPictureBlob(image);
      const ref = await storage.ref().child("imageProfile/");
      const snapshot = await ref.put(blob);
      return await snapshot.ref.getDownloadURL();
    } catch (e) {
      alert("Please Select a Photo First");
      setUploading(false);
      setUpdate(false);
    } finally {
      blob.close();
      setUploading(false);
      setUpdate(false);
      alert("saved successfully");
    }
  };

  const UpdateImage = async () => {
    if (FullName === "") {
      return alert("Plaese update the name or rewrite the old one");
    }
    if (Age === "") {
      return alert("Plaese update the age or rewrite the old one");
    }

    setUpdate(true);
    let imgUrl = await uploadImageToBucket();

    await firebase
      .firestore()
      .collection("users")
      .doc(firebase.auth().currentUser.uid)
      .update({
        photoURL: imgUrl,
        displayName: FullName,
        Email: Email,
        description: Description,
        age: Age,
      })
      .then(() => navigation.navigate("UserProfileScreen"))
      .catch((err) => {
        alert(err, "Please Select a Photo First");
        setUploading(false);
        setUpdate(false);
      });
  };

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