Home > Net >  Uploading file to firebase storage results in null
Uploading file to firebase storage results in null

Time:05-30

I am trying to upload selected image from my phone, using ImagePicker library:

const [bookName, setBookName] = useState("");
const [bookAuthor, setBookAuthor] = useState("");
const [selectedPhoto, setSelectedPhoto] = useState();

const selectPhoto = async () => {
  let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
  if (permissionResult.granted === false) {
    Alert.alert("Permission to access camera roll is required!");
    return;
  }

  let pickerResult = await ImagePicker.launchImageLibraryAsync();

  if (pickerResult.cancelled === true) {
    return;
  }

  setSelectedPhoto(pickerResult);
};

const uploadBook = async () => {
  if (selectedPhoto && bookName !== "" && bookAuthor !== "") {
    const storage = getStorage();
    const uploadUri = Platform.OS === 'ios' ? selectedPhoto.uri.replace('file://', '') : selectedPhoto.uri;

    let bookKey = push(ref(db, 'books/'), {
      name: bookName,
      author: bookAuthor,
      label: '',
    }).key;

    const booksRef = sRef(storage, "books/"   bookKey   '.jpg');
    await uploadBytes(booksRef, uploadUri).then(() => {
      update(ref(db, 'books/'   bookKey), {
        name: bookName,
        author: bookAuthor,
        label: bookKey   '.jpg',
      })
    });
  }
};

Everything working fine, except uploading files. I got file in the storage, which content is 'undefined'. So, how to upload files properly?

P.S. The file is actually available, as I display it after picking

<Image source={{ uri: selectedPhoto.uri }} style={{ width: "100%", height: "100%", resizeMode: "contain" }} />

CodePudding user response:

If you check the documentation for uploadBytes it accepts: Blob | Uint8Array | ArrayBuffer. So it doesn't expect a URL/string value.

You'll want to either create a Blob reference to the selected file, or read the bytes from that file and pass them to Firebase as an ArrayBuffer.

  • Related