Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a file object to a plain object?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading