gpt4 book ai didi

javascript - 使用 React-Native 将图像上传到 Firebase

转载 作者:行者123 更新时间:2023-11-30 20:27:32 28 4
gpt4 key购买 nike

我正在使用这种方法尝试通过我的 React-Native 应用程序将图像上传到 Firebase,因为它似乎是互联网上非常常见的示例,但是我认为它已经很老了,我怀疑它不再适用于较新版本的 React-Native。

谁能告诉我在 Firebase 存储中保存图像的正确方法,谢谢!

 const uploadImage = (uri, imageName, mime = 'image/jpg') => { 

return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '')
: uri;
let uploadBlob = null
const imageRef = firebase.storage().ref('images/').child(imageName)
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, {type: `${mime};BASE64`})
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, {contentType: mime})
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
resolve(url)
})
.catch((error) =>{reject(error)})
})
}

最佳答案

您可以只使用 putFile 方法。

这是我的带有 saveImage 方法的 FirebaseStorageService(我使用的是 RN 0.53 和 react-native-firebase 4.1.0):

saveImage(ref, image, imageName, onSuccess, onError){
LOG.debug("FirebaseStorageService :: saveImage ", {ref:ref, image:image, imageName:imageName});

var firebaseStorageRef = firebase.storage().ref(ref);
const imageRef = firebaseStorageRef.child(imageName + ".jpeg");

LOG.debug("FirebaseStorageService :: imageRef ", {imageRef:imageRef});


imageRef.putFile(image.path, {contentType: 'image/jpeg'}).then(function(){
return imageRef.getDownloadURL();
}).then(function(url){
LOG.debug("Image url", {url:url});
onSuccess(url);
}).catch(function(error){
LOG.error("Error while saving the image.. ", error);
onError(error);
});
}

图片是react-native-image-crop-picker返回的图片.用户可以在打开相机和打开图库之间进行选择,并返回一个图像对象。

图像对象的路径属性只是一个字符串,如 Android 的“file://..”和 iOS 的“/Users/...”。

关于javascript - 使用 React-Native 将图像上传到 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728362/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com