存储的图像被保存为'octet-stream'而不是图像/ jpeg(firebase和ReactNative)



我使用相机(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。图片没有显示,从存储下载时显示未定义。

任何帮助都将非常感激。

我是这样修复的:

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)
}

Reference#put()方法接受BlobUint8ArrayArrayBuffer。你的"file"对象似乎不属于这些。

相反,我们需要将文件读入内存(使用react-native-fs—称为RNFS),然后将该数据与所需的元数据一起上传。因为RNFS将文件读取为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()
}
});
};

解决方案:uploadBytesResumable()方法中的图像引用

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

相关内容

  • 没有找到相关文章

最新更新