Next.js Discord

Discord Forum

Passing file to server action for upload?

Unanswered
American Shorthair posted this in #help-forum
Open in Discord
Avatar
American ShorthairOP
I'm having an issue figuring out if it's possible to pass an image to a server action for upload to database. If possible, id like to do this server side to avoid loading the firebase packages client side but I keep getting this error

Application error: a client-side exception has occurred (see the browser console for more information).


react-dom.development.js:7749 Uncaught Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.
    at Array.resolveToJSON (react-server-dom-webpack-client.browser.development.js:732:31)


Here is my server action attempt
'use server';

import { storage } from './firebase';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';

export async function uploadFileToFirebase(file, path) {
  const storageRef = ref(storage, `${path}`);

  try {
    const snapshot = await uploadBytes(storageRef, file);
    const downloadURL = await getDownloadURL(snapshot.ref);
    console.log('File uploaded!', downloadURL);

    return downloadURL;
  } catch (error) {
    console.error('Error uploading file:', error);
    throw error; 
  }
}


handle drop from mui file drop component
  const handleDrop = useCallback(
    async (acceptedFiles) => {
      const file = acceptedFiles[0];
      if (!file) return;

      try {
        const downloadURL = await uploadFileToFirebase(
          file,
          `blog/${currentPost.urlTitle}/cover-image`
        );

        const newFile = {
          ...file,
          preview: downloadURL,
        };
      } catch (error) {
       
      }
    },
    [setValue, currentPost.urlTitle]
  );

1 Reply

Avatar
American ShorthairOP
So I was able to finally get it to work by passing the file in with all the form data then accessing the file that way. Not sure if there is a better way, but this is the only way i could find to get it work. still open to hearing a better way if anybody has it. Thank you