错误:服务器操作要求将请求体解析为 FormData 或 JSON。收到意外的内容类型:multipart/form-data
Error: Server Actions require the request body to be parsed as FormData or JSON. Received unexpected content type: multipart/form-data
ID: nextjs/server-action-formdata-multipart
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Next.js 14.0.0 | active | — | — | — |
| Next.js 14.1.0 | active | — | — | — |
| Next.js 14.2.0 | active | — | — | — |
根因分析
服务器操作被调用时使用了 multipart/form-data 请求(例如,来自没有正确编码的文件上传表单),但服务器操作仅支持 application/x-www-form-urlencoded、text/plain 或 application/json 内容类型。不支持 multipart/form-data。
English
A Server Action is called with a multipart/form-data request (e.g., from a file upload form without proper encoding), but Server Actions only support application/x-www-form-urlencoded, text/plain, or application/json content types. multipart/form-data is not supported.
官方文档
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#formdata解决方案
-
从表单中移除文件输入,并通过 API 路由单独处理文件上传。示例:仅对文本字段使用带有 action={serverAction} 的标准表单,并添加单独的文件上传组件,该组件向 /api/upload 发送 POST 请求。 -
在调用服务器操作之前,在客户端处理程序中将表单数据转换为 JSON。示例:`const formData = new FormData(event.target); const json = Object.fromEntries(formData.entries()); await serverAction(json);`
-
在 API 路由中使用第三方库(如 'formidable')处理 multipart 上传,然后从 API 路由中使用解析后的数据以 JSON 格式调用服务器操作。
无效尝试
常见但无效的做法:
-
100% 失败
Multipart/form-data is the default for forms with file inputs, but Server Actions reject it; the form must be sent as URL-encoded or plain text.
-
90% 失败
If the fetch still sends multipart/form-data (the default for FormData), the same error occurs. The fetch must explicitly set Content-Type to application/json.
-
100% 失败
HTML forms do not support JSON enctype; the browser will ignore it and use the default (application/x-www-form-urlencoded for non-file forms, multipart/form-data for file forms).