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

FastAPI返回的Blob图片在Next.js中无法显示的问题求助

问题原因及解决方案

为什么会报错?

URL.createObjectURL()生成的Blob URL是当前运行环境的本地资源标识。你的代码是在Next.js Server Action(Node.js服务器环境)里调用的这个方法,生成的blob:nodedata:... URL只能在Node.js进程内部使用,浏览器客户端完全无法识别这个协议的资源,自然会抛出"Not allowed to load local resource"的错误。

三种可行的解决方案

方案1:返回Base64编码的Data URI

在Server Action里把FastAPI返回的图片转成Base64格式的Data URI,直接传给客户端,浏览器可以直接解析这个格式的地址:

// Server Action 代码
async function getImageUrl() {
  const response = await fetch('https://你的FastAPI接口地址');
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  const base64Str = buffer.toString('base64');
  return `data:image/jpeg;base64,${base64Str}`;
}

客户端组件直接将返回值赋值给<img>的src属性即可。

方案2:客户端直接请求FastAPI接口

如果FastAPI接口配置了跨域(CORS),可以让客户端直接发起请求,在浏览器环境生成Blob URL:

// 客户端组件代码
async function loadImage() {
  const res = await fetch('https://你的FastAPI接口地址');
  const blob = await res.blob();
  const imageUrl = URL.createObjectURL(blob);
  // 将imageUrl赋值给img元素的src
}

FastAPI配置CORS的示例代码:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境建议指定具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

方案3:用Next.js API路由做代理

如果需要对请求做权限校验,或者不想暴露FastAPI的地址,可以创建Next.js的API路由作为代理,直接把图片响应返回给客户端:

// app/api/proxy-image/route.js
export async function GET() {
  const fastApiRes = await fetch('https://你的FastAPI接口地址');
  const blob = await fastApiRes.blob();
  return new Response(blob, {
    headers: { 'Content-Type': 'image/jpeg' }
  });
}

客户端直接使用这个代理地址作为图片源:

<img src="/api/proxy-image" alt="示例图片" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:57:21