我尝试使用我的expo应用程序将图像上传到firebase存储器。我浏览了他们的文档,并尝试使用文档实现。但无论何时上传,我都没有收到任何错误,但出现在firebase上的图像只是一个普通的白色框
图像上传至Firebase
查看预览时出错
这是我的全部代码
import React, { useState } from 'react';
import { Image, View, Text, Button, ActivityIndicator } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { app } from './firebaseConfig';
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import 'firebase/storage';
const App = () => {
const [image, setImage] = useState(null);
const [uploading, setUploading] = useState(false);
const pickImage = async () => {
try {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.canceled) {
console.log(result.assets[0].uri)
setImage(result.assets[0].uri);
}
} catch (E) {
console.log(E);
}
};
const storage = getStorage(app);
// Create the file metadata
/** @type {any} */
const metadata = {
contentType: 'image/jpeg'
};
// Upload file and metadata to the object 'images/mountains.jpg'
const storageRef = ref(storage, 'images/' + Date.now());
const uploadTask = uploadBytesResumable(storageRef, image, metadata);
console.log(storageRef)
// Listen for state changes, errors, and completion of the upload.
uploadTask.on('state_changed',
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% 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);
});
}
);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && (
<>
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
</>
)}
{uploading && <ActivityIndicator />}
</View>
);
};
export default App;
1条答案
按热度按时间mf98qq941#
由
expo-image-picker
返回的URL路径result.assets[0].uri
是对图像数据的引用,但不包含实际的图像数据。由于firebase希望上传二进制数据,因此应用需要首先获取图像二进制数据。
我写过一篇关于这个主题的深入文章-https://dev.to/emmbyiringiro/upload-image-with-expo-and-firebase-cloud-storage-3481