我试图找到一种有效的方法,在我上传图片后立即在Firebase中获取图片的网址。 我想避免为此编写一个完全独立的函数....相反,Id 喜欢将其包含在承诺链中。 请参阅下面的代码
import storage from '@react-native-firebase/storage';
storage()
.ref('path/to/remote/folder')
.putFile('uri/of/local/image')
.then(() => {
//Id like to use getDownloadUrl() function here;
})
您可以使用await
创建承诺链,然后轻松获取下载网址,如下所示:
/**
* Upload the image to the specific firebase path
* @param {String} uri Uri of the image
* @param {String} name Name of the image
* @param {String} firebasePath Firebase image path to store
*/
const uploadImage = async (uri, name, firebasePath) => {
const imageRef = storage().ref(`${firebasePath}/${name}`)
await imageRef.putFile(uri, { contentType: 'image/jpg'}).catch((error) => { throw error })
const url = await imageRef.getDownloadURL().catch((error) => { throw error });
return url
}
现在你可以按如下方式调用这个函数:
const uploadedUrl = await uploadImage('uri/of/local/image', 'imageName.jpg', 'path/to/remote/folder');
现在uploadedUrl
将包含上传图像的 url。
来自Kishan的好答案,但对我不起作用....下面包括一些小的修改,所以对我有用。
const localUri = Platform.OS === 'ios' ? imgPickResponse.uri.replace('file://', '') : imgPickResponse.uri;
this.uploadImageAndGetUrl(localUri, '/profilePics/' + this.props.userId)
.then(url => {console.log(url);});
}
uploadImageAndGetUrl = async (localUri, firebasePath) => {
try {
const imageRef = storage().ref(firebasePath);
await imageRef.putFile(localUri, {contentType: 'image/jpg'});
const url = await imageRef.getDownloadURL();
return url;
} catch (err) {
Alert.alert(err);
}
};
就我而言,uri 在 Android 权限方面抛出了错误。所以以下功能对我有用。我没有 uri,而是从 ImagePicker 传递了 response.path。提示:您可以使用 uuid 生成随机文件名。
this.uploadAndReturnFirestoreLink(response.path, 'images/' + 'example.jpg')
uploadAndReturnFirestoreLink = async (loaclPath, folderPath) => {
console.log(loaclPath)
try {
const imageRef = storage().ref(folderPath);
await imageRef.putFile(loaclPath, { contentType: 'image/jpg' });
const url = await imageRef.getDownloadURL();
console.log(url)
alert('Upload Success', url)
} catch (e) {
console.log(e);
}
};