Search code examples
next.jsnext-authremix.run

Send an Audio File in a multipart/form-data Form POST Using Remix.run (1.16)


I'm trying to send an audio file to the server side through a post request of a form.

I'm trying to use unstable_parseMultipartFormData in conbination with multipart/form-data Form as instructed on Remix documentation here but I get this error: TypeError: uploadHandler2 is not a function at parseMultipartFormData

Im trying to use this file on server side inside the action.

export const action = async ({ request, context }) => {
   const formData = await unstable_parseMultipartFormData(
      request,
      uploadHandler
   );
   return ''
};

export default function Index() {
   const submit = useSubmit()
   const [formData, setFormData] = useState({
      audioFile: '',
   });

   const handleFileChange = (event) => {
      setFormData({ audioFile: event.target.files[0] });
   };

   const handleSubmit = async (e) => {
      e.preventDefault();
      submit(formData, { method: "post" });
   };

   return (
      <>
         <section>
            <Form encType="multipart/form-data" method="POST" >
               <input
                  id="fileUpload"
                  name="audioFile"
                  type="file"
                  accept=".mp3,.m4a"
                  // onChange={handleFileChange}
                  className="bg-neutral-600 text-white px-4 py-2 rounded-lg mb-4 w-full text-sm"
               />
               <button className="text-white border border-white p-2 rounded-md text-sm" type="submit">Send</button>
            </Form>

         </section>
      </>
   );
}

Help is be greatly appreciated.

Thank you.


Solution

  • To upload files, you need to set the <Form encType>:

    <Form method="post" encType="multipart/form-data">
      <input type="file" name="audioFile" />
      <button>Submit</button>
    </Form>
    

    Then create an action with an uploadHandler:

    import { 
      unstable_createMemoryUploadHandler,
      unstable_parseMultipartFormData, 
    } from '@remix-run/node';
    
    export const action = async ({ request }: ActionArgs) => {
      const uploadHandler = unstable_createMemoryUploadHandler({
        maxPartSize: 500_000,
      });
      const formData = await unstable_parseMultipartFormData(
        request,
        uploadHandler
      );
      // now you can get the audio file as a File object
      const audioFile = formData.get("audioFile") as File;
      ...
    }
    

    https://remix.run/docs/en/1.16.1/utils/parse-multipart-form-data