存储的图像保存为“八位字节流”,而不是图像/jpeg(firebase和ReactNative)

b4lqfgs4  于 2022-12-27  发布在  React
关注(0)|答案(3)|浏览(166)

我正在使用相机(react-native-image-Picker)进行选择并将其保存到存储中。

const saveImage = async () => {
    const id = firebase.firestore().collection('food').doc().id
    const storageRef = firebase.storage().ref()
    const fileRef = storageRef.child(file.fileName) //name of image to store
    await fileRef.put(file) //store image

    firebase.firestore().collection("food").doc(id).update({
      image: firebase.firestore.FieldValue.arrayUnion({
        name: file.fileName,
        url: await fileRef.getDownloadURL()
      })
    })
}
console.log(typeof file);
gives => "object"

console.log(file);
//gives => 
file = {height: 2322, 
uri:"content://com.photodocumentation.imagepickerprovidlib_temp_7a0448df-1fac-4ac7-a47c-402c62ecce4c.jpg", 
width: 4128, 
fileName: "rn_image_picker_lib_temp_7a0448df-1fac-4ac7-a47c-402c62ecce4c.jpg", 
type: "image/jpeg"}

结果:在Firebase(存储)中,图像被保存为application/octet-stream,而不是image/jpeg。图像未显示,从存储中下载时显示未定义。
任何帮助都将不胜感激。

ej83mcc0

ej83mcc01#

这是我如何能够修复它:

const uploadImage = async () => {
    const response = await fetch(file.uri)
    const blob = await response.blob();
    var ref = firebase.storage().ref().child("FolderName");
    return ref.put(blob)
}
9jyewag0

9jyewag02#

Reference#put()方法接受BlobUint8ArrayArrayBuffer。您的“file”对象似乎不是其中任何一个。
相反,我们需要将文件读入内存(使用react-native-fs-称为RFS),然后上传数据沿着所需的元数据。由于RFS将文件读取为Base64,因此我们将使用Reference#putString,因为它接受Base64字符串进行上传。

const rnfs = require('react-native-fs');

const saveImage = async () => {
  const capture = /* this is your "file" object, renamed as it's not a `File` object */
  const fileRef = firebase.storage().ref(capture.fileName);
  const captureBase64Data = await rnfs.readFile(capture.uri, 'base64');
  const uploadSnapshot = await fileRef.putString(captureBase64Data, 'base64', {
    contentType: capture.type,
    customMetadata: {
      height: capture.height,
      width: capture.width
    }
  });

  // const id = colRef.doc().id and colRef.doc(id).update() can be replaced with just colRef.add() (colRef being a CollectionReference)

  return await firebase.firestore().collection('food').add({
    image: {
      name: capture.fileName,
      url: await fileRef.getDownloadURL()
    }
  });
};
20jt8wwn

20jt8wwn3#

溶液:uploadBytesResumable()方法中的图像引用

const storageRef = ref(storage,`product-images/${image.name}`);
uploadBytesResumable(storageRef,image);

相关问题