I need to convert a file object from an input to a plain object to upload it to firestore using react:
await setDoc(doc(db, "users", userId, "images", file.name), file)
But get this error:
FirebaseError: Function setDoc() called with invalid data. Data must
be an object, but it was: a custom File object
Is there a way to do it?
>Solution :
To upload a File object directly to Firestore, but Firestore expects the data to be in the form of a plain JavaScript object. To achieve this, you need to convert the File object into a format that Firestore can handle, such as converting it to a Blob or a base64-encoded string.
import { doc, setDoc } from 'firebase/firestore';
import { getDownloadURL, ref, uploadString } from 'firebase/storage';
import { db, storage } from './firebase'; // Your Firebase configuration
async function uploadFileToFirestore(file, userId) {
const reader = new FileReader();
reader.onload = async (event) => {
const base64Data = event.target.result.split(',')[1]; // Extract base64 data from Data URL
try {
// Upload the base64 data to Firebase Storage
const storageRef = ref(storage, `users/${userId}/images/${file.name}`);
await uploadString(storageRef, base64Data, 'base64');
// Get the download URL from Storage
const downloadURL = await getDownloadURL(storageRef);
// Create a plain object with the download URL
const imageData = {
name: file.name,
url: downloadURL,
};
// Upload the object to Firestore
await setDoc(doc(db, 'users', userId, 'images', file.name), imageData);
console.log('File uploaded successfully!');
} catch (error) {
console.error('Error uploading file:', error);
}
};
reader.readAsDataURL(file);
}