目标:
使用Expo ImagePicker从本地存储(IOS模拟器)中选择一个映像并将其上传到Firebase存储
控制台输出:
Upload is 0% done
Upload is running
但它卡在那里,图像无法上传
首先,我调用这个函数从本地存储中选择一个图像并检索blob,图像在屏幕上显示良好,如果我试图控制台记录blob,我会得到一个错误,说它不能显示,我猜是因为它是一个blob
async function pickImage() {
result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
let imageFile = await fetch(result.uri);
let imageBlob = await imageFile.blob()
setBlob(imageBlob)
}
}
然后我尝试上传到Firebase存储:
function uploadToFirebase(){
const storageRef = ref(storage, 'anything.jpg');
const uploadTask = uploadBytesResumable(storageRef, blob);
uploadTask.on('state_changed',
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
setImageProgress((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
console.log('Upload is ' + imageProgress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log('File available at', downloadURL);
setLoadedImage(downloadURL)
});
}
);
}
我已经尝试了每一个迭代,这我可以找到网上,但无济于事
2条答案
按热度按时间ql3eal8s1#
我也遇到了同样的问题。在搜索了不同的主题后,我找到了答案。下面的代码将图像上传到Firebase存储
注意:pickImageResult.uri 是ImagePicker.launchImageLibraryAsync()的镜像结果;
jtoj6r0c2#
有几个方法你可以试试。我看过其他的答案,也试过了,但有时也会失败。这里有几个方法你可以先试试。
1.将contentType元数据添加到您的上载。
1.存储最好接受png文件。如果你能重新格式化它们,用Expo manipulateAsync()。
1.切换到react-native-firebase。现在用cli builds管理expo应用非常容易。
1.我确信这只是一个firestore/realtime的东西,但是我现在从我上传到firebase服务的任何东西中删除未定义的键。有时候,我使用的键在图像上是未定义的,所以我只是在后面的前端说明这一点。
介绍用于图像上传的1和2
视频上传给了我更多的麻烦,这是我的解决方案:
1.删除未定义的键。
我先给了你TLDR
下面是上传到存储桶的实际函数
希望这对你有帮助!