next.js 使用www.example.com在multipart/form-data表单POST中发送音频文件Remix.run(1.16)

cgyqldqp  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(95)

我试图通过表单的post请求将音频文件发送到服务器端。
我试图按照Remix文档here上的说明将unstable_parseMultipartFormData与multipart/form-data Form结合使用,但我得到了这个错误:TypeError:uploadHandler 2不是parseMultipartFormData的函数
我试图使用这个文件在服务器端内的行动。

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>
      </>
   );
}

非常感谢您的帮助。
谢谢你。

beq87vna

beq87vna1#

要上传文件,需要设置<Form encType>

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

然后用uploadHandler创建一个action:

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

相关问题