FastAPI接收大Base64 GIF字符串报RemoteProtocolError问题求助
解决FastAPI接收大Base64 GIF字符串时的RemoteProtocolError问题
我用FastAPI写了个API,接收Base64格式的GIF字符串作为输入。现在遇到个问题:传入小或中等大小的字符串时API能正常运行并返回响应,但传入较大的字符串时会触发错误:raise RemoteProtocolError(h11._util.RemoteProtocolError: Receive buffer too long)。
我的代码如下:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse import base64 app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials= True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/myapp",response_class=FileResponse) async def detection(gif_url: str,img_url: str): gif_data = base64.b64decode(gif_url) gif_data_file = open("source.gif", "wb") gif_data_file.write(gif_data) return {"message":"Gif saved"}
gif_url 用于接收Base64格式的GIF字符串。
问题原因
这个错误的核心是GET请求的URL长度限制。GET请求的参数是直接拼接在URL中的,而浏览器、FastAPI默认使用的Uvicorn服务器都有URL长度的默认上限。Base64编码会让原文件体积膨胀约33%,大GIF的Base64字符串很容易突破这个上限,导致缓冲区溢出触发错误。
解决办法
方案1:改用POST请求传递数据(推荐)
GET本就不适合传输大量数据,把接口改成POST,用请求体来接收Base64字符串,这样就不受URL长度限制了。修改后的代码如下:
from fastapi import FastAPI, Body, BaseModel from fastapi.middleware.cors import CORSMiddleware import base64 app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 定义请求体模型,规范参数结构 class GifRequest(BaseModel): gif_url: str img_url: str @app.post("/myapp") async def detection(request: GifRequest): # 用with语句自动管理文件,避免资源泄漏 with open("source.gif", "wb") as gif_data_file: gif_data_file.write(base64.b64decode(request.gif_url)) return {"message": "Gif saved"}
如果不想定义模型,也可以直接用Body参数接收:
@app.post("/myapp") async def detection(gif_url: str = Body(...), img_url: str = Body(...)): with open("source.gif", "wb") as gif_data_file: gif_data_file.write(base64.b64decode(gif_url)) return {"message": "Gif saved"}
方案2:调整服务器缓冲区大小(不推荐作为主要方案)
如果一定要保留GET请求,可以通过Uvicorn的启动参数增大请求缓冲区上限,比如:
uvicorn main:app --max-request-size 100MB
但这种方法治标不治本——大部分浏览器的URL长度上限在2KB到8KB之间,大Base64字符串依然会被浏览器截断,无法正常发送请求。
内容的提问来源于stack exchange,提问作者Ali Ahmad
相关产品推荐
相关产品推荐

