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

React中浏览器上传图片至GoogleAIFileManager的报错解决咨询

解决浏览器环境下GoogleAIFileManager上传用户图片的问题

问题原因

GoogleAIFileManager.uploadFile方法默认针对Node.js环境实现,依赖fs.readFileSync读取本地文件路径。在浏览器环境中没有fs模块,直接传递文件名或错误的参数类型会触发TypeError: (0 , import_fs.readFileSync) is not a function错误。

解决方案

在浏览器中,需要将用户上传的File对象转换为ArrayBuffer(浏览器兼容的二进制数据格式),再传递给uploadFile方法,同时正确配置文件参数。

修正后的完整代码

React组件中的文件输入与处理函数

import { GoogleAIFileManager } from '@google/generative-ai';

const ImageUploadComponent = () => {
  const handleImageUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
      await googleFileUpload(file);
    } catch (error) {
      console.error('图片上传失败:', error);
    }
  };

  async function googleFileUpload(file) {
    const fileManager = new GoogleAIFileManager(import.meta.env.VITE_GEMINI_KEY);
    
    // 将用户上传的File对象转换为ArrayBuffer
    const fileBuffer = await file.arrayBuffer();
    
    // 上传文件,传递ArrayBuffer而非文件路径
    const uploadResult = await fileManager.uploadFile(fileBuffer, {
      mimeType: file.type, // 从File对象自动获取正确的MIME类型
      displayName: file.name, // 使用原文件名作为显示名称
    });

    console.log(`上传成功:${uploadResult.file.displayName},文件URI:${uploadResult.file.uri}`);
    return uploadResult;
  }

  return (
    <input
      type="file"
      accept="image/*"
      onChange={handleImageUpload}
    />
  );
};

export default ImageUploadComponent;

关键注意事项

  • 避免硬编码MIME类型:使用file.type获取上传文件的实际MIME类型,适配JPEG、PNG等多种图片格式
  • 使用ArrayBuffer传递文件内容:浏览器环境下通过file.arrayBuffer()读取二进制数据,绕过Node.js的fs依赖逻辑
  • 版本兼容性:确保使用的@google/generative-ai包为最新版本,旧版本可能存在浏览器环境适配问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:32:34