Firestore 是 Firebase 提供的一个 NoSQL 数据库服务,而 Firebase 存储则是一个用于存储和检索文件的云服务。在 React 应用中,你可以将图片上传到 Firebase 存储,并获取图片的 URL,然后将该 URL 保存到 Firestore 中。
以下是一个示例代码,展示如何在 React 应用中上传图片到 Firebase 存储,并将图片 URL 保存到 Firestore 中。
首先,确保你已经安装了 Firebase 和 React 相关的依赖:
npm install firebase react
在你的 React 项目中初始化 Firebase:
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/storage';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
const storage = firebase.storage();
import React, { useState } from 'react';
const UploadImage = () => {
const [image, setImage] = useState(null);
const [imageUrl, setImageUrl] = useState('');
const handleImageChange = (e) => {
setImage(e.target.files[0]);
};
const uploadImage = async () => {
if (!image) return;
const storageRef = storage.ref().child(image.name);
const uploadTask = storageRef.put(image);
uploadTask.on('state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
},
(error) => {
console.error(error);
},
() => {
uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
setImageUrl(downloadURL);
saveImageUrlToFirestore(downloadURL);
});
}
);
};
const saveImageUrlToFirestore = async (url) => {
try {
await firestore.collection('images').add({
url: url,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
console.log('Image URL saved to Firestore');
} catch (error) {
console.error('Error saving image URL to Firestore:', error);
}
};
return (
<div>
<input type="file" onChange={handleImageChange} />
<button onClick={uploadImage}>Upload</button>
{imageUrl && <img src={imageUrl} alt="Uploaded" />}
</div>
);
};
export default UploadImage;
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云