You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS上传12MB CSV文件报413错误,旧配置已废弃求助

解决Next.js App Router API路由413 Payload Too Large错误

问题场景

上传12MB CSV文件至API路由时触发413错误,原有的export const config配置写法已被标记为废弃,且新文档未明确说明请求体大小限制的调整方式。

可行解决方案

方案1:全局配置(通过next.config.js)

在项目根目录的next.config.js中添加全局请求体大小限制,对所有API路由生效:

/** @type {import('next').NextConfig} */
const nextConfig = {
  serverRuntimeConfig: {
    bodyParser: {
      sizeLimit: '15mb'
    }
  }
}

module.exports = nextConfig

方案2:单路由自定义解析(绕过默认限制)

针对特定API路由禁用默认body解析,手动处理文件上传,彻底避开Next.js的内置大小限制:

  1. 禁用默认body解析(此写法虽提示旧版,但仍被允许用于关闭默认解析):
// app/api/upload/route.ts
export const config = {
  api: {
    bodyParser: false,
  },
};
  1. 使用原生formData处理上传(示例):
import { NextResponse } from 'next/server';
import { writeFile } from 'fs/promises';
import { join } from 'path';

export async function POST(request: Request) {
  const formData = await request.formData();
  const file = formData.get('file') as File;

  if (!file) {
    return NextResponse.json({ error: '未上传文件' }, { status: 400 });
  }

  // 处理文件(示例:保存到本地)
  const buffer = Buffer.from(await file.arrayBuffer());
  const savePath = join(process.cwd(), 'public', 'uploads', file.name);
  await writeFile(savePath, buffer);

  return NextResponse.json({ message: '文件上传成功' });
}

方案3:边缘运行时适配

若使用Edge Runtime,可通过next.config.js的headers配置调整请求大小限制:

const nextConfig = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          { key: 'Max-Content-Length', value: '15728640' }, // 15MB(字节数)
        ],
      },
    ];
  },
};

module.exports = nextConfig;

注意事项

  • 旧版bodyParser.sizeLimit的路由级配置已废弃,官方推荐全局配置或自定义解析方案。
  • 自定义解析时需确保服务器有足够的临时存储资源处理大文件。

内容的提问来源于stack exchange,提问作者BRS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:20:10