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

如何配置Plug.Parsers支持大文件上传?遇RequestTooLargeError求助

解决Plug.Parsers.RequestTooLargeError问题

你的问题出在Phoenix Endpoint中默认的Plug.Parsers配置优先级更高,Router里admin pipeline的配置根本没机会生效。默认情况下,Endpoint里的Plug.Parsers限制请求大小为8MB,当你上传超过这个大小的文件时,在请求到达Router之前就会触发报错。

解决方案

方案一:仅针对/admin路径放宽限制(推荐)

在lib/monolith_web/endpoint.ex中,全局Plug.Parsers配置之前,添加针对/admin路径的单独解析器配置:

# 先处理/admin路径的大文件请求
plug Plug.Parsers,
  parsers: [:url_encoded, :multipart],
  length: 200_000_000, # 调整为你需要的大小(单位:字节,示例为200MB)
  only: "/admin"

# 全局默认解析器配置(保持原有内容即可)
plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json],
  pass: ["*/*"],
  json_decoder: Phoenix.json_library()

然后删除Router中admin pipeline里的plug Plug.Parsers配置,避免重复解析:

defmodule MonolithWeb.Router do
  use MonolithWeb, :router
  use Kaffy.Routes, scope: "/admin", pipe_through: [:admin, :authenticate]

  pipeline :admin do
    # 移除重复的Plug.Parsers配置
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug :fetch_current_user
  end
end

方案二:全局放宽请求大小(不推荐)

如果所有请求都需要支持大文件上传,可以直接修改Endpoint里的全局Plug.Parsers配置,添加length参数:

plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json],
  pass: ["*/*"],
  length: 200_000_000, # 按需调整大小
  json_decoder: Phoenix.json_library()

同样需要删除Router中admin pipeline里重复的Plug.Parsers配置。

注意事项

  • length参数的单位是字节,200_000_000等于200MB,根据你的实际需求调整,不要设置过大(比如你写的200GB可能没必要,还会带来安全风险)。
  • 修改配置后需要重启Phoenix服务才能生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:54:25