将文件上传到 firebase 存储导致 null

Uploading file to firebase storage results in null

我正在尝试使用 ImagePicker 库从我的 phone 上传所选图片:

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',
      })
    });
  }
};

一切正常,除了上传文件。我在存储中得到了文件,内容是'undefined'。那么,如何正确上传文件呢?

P.S。该文件实际上是可用的,因为我选择后显示它

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

如果您选中 documentation for uploadBytes,它会接受:Blob | Uint8Array | ArrayBuffer。所以它不期望 URL/string 值。

您需要创建对所选文件的 Blob 引用,或者从该文件读取字节并将它们作为 ArrayBuffer.

传递给 Firebase