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

如何通过API向Google Gemini模型传入文件实现多模态交互?

解决Gemini无法通过GCS链接读取附件的方案

问题核心

Gemini的多模态API不支持访问外部URL(包括Google Cloud Storage链接),必须直接传入文件的二进制/编码内容才能解析处理。

可行方案:直接上传文件内容至Gemini API

结合你的技术栈(Next.js、Firebase Cloud Functions/Vercel),可以按以下流程实现:

1. 客户端(Next.js)处理

  • 用户选择本地文件后,通过FileReader读取文件内容并转换为base64编码
  • 将提示文本、base64编码的文件内容、文件MIME类型一起发送到后端API(Cloud Functions或Vercel路由)

示例代码(Next.js客户端):

async function handleFileSubmit(prompt, file) {
  const reader = new FileReader();
  reader.onload = async (e) => {
    const base64Data = e.target.result.split(',')[1]; // 提取base64编码部分
    const response = await fetch('/api/gemini-request', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt,
        fileData: base64Data,
        mimeType: file.type
      })
    });
    const result = await response.json();
    // 处理Gemini返回的结果
  };
  reader.readAsDataURL(file);
}

2. 服务端(Cloud Functions/Vercel API)处理

  • 接收客户端的请求数据,将base64解码为二进制数据
  • 使用Google Generative AI库构造包含文件的多模态请求,直接传入文件内容
  • 调用Gemini API并返回结果

示例代码(Cloud Functions Node.js):

const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

exports.geminiFileRequest = async (req, res) => {
  const { prompt, fileData, mimeType } = req.body;
  // 选择支持多模态的Gemini模型
  const model = genAI.getGenerativeModel({ model: 'gemini-pro-vision' });

  const filePart = {
    inlineData: {
      data: fileData,
      mimeType
    }
  };

  const result = await model.generateContent([prompt, filePart]);
  const response = await result.response;
  const text = response.text();

  res.json({ result: text });
};

方案优势

  • 完全利用Gemini原生的多模态解析能力,无需客户端额外转换文本
  • 避免使用Document AI的额外成本,直接通过Gemini API处理PDF、图片、XLS文件
  • 适配你的现有技术栈,无需引入新的服务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:08:27