# 错误：服务器操作要求将请求体解析为 FormData 或 JSON。收到意外的内容类型：multipart/form-data

- **ID:** `nextjs/server-action-formdata-multipart`
- **领域:** nextjs
- **类别:** protocol_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

服务器操作被调用时使用了 multipart/form-data 请求（例如，来自没有正确编码的文件上传表单），但服务器操作仅支持 application/x-www-form-urlencoded、text/plain 或 application/json 内容类型。不支持 multipart/form-data。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Next.js 14.0.0 | active | — | — |
| Next.js 14.1.0 | active | — | — |
| Next.js 14.2.0 | active | — | — |

## 解决方案

1. ```
   从表单中移除文件输入，并通过 API 路由单独处理文件上传。示例：仅对文本字段使用带有 action={serverAction} 的标准表单，并添加单独的文件上传组件，该组件向 /api/upload 发送 POST 请求。
   ```
2. ```
   在调用服务器操作之前，在客户端处理程序中将表单数据转换为 JSON。示例：`const formData = new FormData(event.target); const json = Object.fromEntries(formData.entries()); await serverAction(json);`
   ```
3. ```
   在 API 路由中使用第三方库（如 'formidable'）处理 multipart 上传，然后从 API 路由中使用解析后的数据以 JSON 格式调用服务器操作。
   ```

## 无效尝试

- **** — 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. (100% 失败率)
- **** — 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. (90% 失败率)
- **** — 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). (100% 失败率)
