如何使用 React hook 表单和 next.js 14 个服务器操作处理客户端上的文件上传

问题描述 投票:0回答:1

我有一个使用 next.js 14 的 React Hook 表单注册的文件输入

"use client"
..........more code  
  <form action={handleSubmit(updateUserProfile)}>
        <input
                    {...register("avatar_url")}
                    type="file"
                    name="avatar_url"
                    accept="image/*"                
                  />
        <button type="submit">upload</button>
    </from>
......rest of the code goes here

下面是我的异步函数

 async function updateUserProfile(formData) {
    // updateCurrentUserProfile is server action with supabase storage api, w/ server client
    const response = await updateCurrentUserProfile(formData);
  }

如果我不选择任何文件,那么它会顺利运行,不会出现任何错误。但如果我选择要上传的文件。我收到错误

Application error: a client-side exception has occurred (see the browser console for more information).
Uncaught Error: Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.

我不想创建任何路由处理程序。我想仅使用服务器操作上传图像。我尝试构造一个新的 FormData,但这并没有将文件传递给服务器操作,而是只是发送一个空的 FileList 对象数组。

reactjs next.js serialization server-side-rendering
1个回答
0
投票

尝试使用 RHF 和服务器操作上传图像时遇到同样的问题。

我的解决方法是:

 const onSubmit: SubmitHandler<FormTypes> = async data => {
 // ? workaround to upload the images with server action and RHF
 const formData = new FormData()
 data.documents.forEach((document) => {
   formData.append('documents', document)
 })

 const formData: FormTypes = JSON.parse(JSON.stringify(data))
 const request = await serverActionFunction(data, formData)
 console.log(request)
}

服务器操作:

const serverActionFunction = (data: FormTypes, formData: FormData) => {
 return {data, formData}
}
© www.soinside.com 2019 - 2024. All rights reserved.