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

NextJS中如何向后端API发送超过1MB的图片?

解决NextJS上传图片到Cloudinary时的413请求过大错误

1. 调整NextJS API路由的请求大小限制

NextJS 默认对API路由的请求体大小限制为1MB,这是触发413错误的核心原因。你可以通过两种方式修改:

全局配置(next.config.js)

在项目根目录的next.config.js中添加配置,设置更大的请求体上限(比如10MB):

/** @type {import('next').NextConfig} */
const nextConfig = {
  api: {
    bodyParser: {
      sizeLimit: '10mb',
    },
  },
};

module.exports = nextConfig;

单个API路由单独配置

如果只想针对上传图片的API路由放宽限制,可以在对应API文件中禁用默认bodyParser,手动处理请求:

import formidable from 'formidable';
import cloudinary from 'cloudinary';

cloudinary.config({
  cloud_name: '你的cloud_name',
  api_key: '你的api_key',
  api_secret: '你的api_secret',
});

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(req, res) {
  const form = new formidable.IncomingForm({
    maxFileSize: 10 * 1024 * 1024, // 10MB
  });

  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    try {
      const result = await cloudinary.uploader.upload(files.image.filepath);
      res.status(200).json({ url: result.secure_url });
    } catch (uploadErr) {
      res.status(500).json({ error: uploadErr.message });
    }
  });
}

2. 放弃Base64,改用FormData上传二进制文件

Base64编码会让文件体积增加约30%,比如原本900KB的图片转成Base64后会超过1MB,直接触发限制。改用FormData上传原始二进制文件更高效,还能避免体积膨胀:

前端上传代码示例

async function uploadImage(file) {
  const formData = new FormData();
  formData.append('image', file);

  const response = await fetch('/api/upload', {
    method: 'POST',
    body: formData,
  });

  if (!response.ok) {
    throw new Error('上传失败');
  }
  return response.json();
}

3. 前端图片压缩(可选)

如果用户上传的图片本身过大,可以在前端先压缩,进一步减小文件体积:

async function compressImage(file, quality = 0.7) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const img = new Image();
      img.src = e.target.result;
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        // 保持宽高比,限制最大宽度为1920px
        const maxWidth = 1920;
        let width = img.width;
        let height = img.height;
        if (width > maxWidth) {
          height = (height * maxWidth) / width;
          width = maxWidth;
        }
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);
        canvas.toBlob(
          (blob) => resolve(new File([blob], file.name, { type: file.type })),
          file.type,
          quality
        );
      };
    };
    reader.readAsDataURL(file);
  });
}

// 使用示例
const compressedFile = await compressImage(selectedFile);
await uploadImage(compressedFile);

4. 检查Cloudinary的上传限制(确认项)

虽然问题大概率出在NextJS的限制,但可以确认下Cloudinary的账户设置:登录Cloudinary控制台,进入「Settings > Upload」,查看「Maximum file size」是否设置过低,调整到合适数值(比如10MB)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:54:43