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

如何在ReactJs中集成Cloud Document AI API?求具体流程

在React中集成Cloud文档AI API的完整流程

当然可以在React中集成Cloud文档AI API,由于前端直接调用会存在密钥泄露的安全风险,通常的做法是通过后端中转来实现,以下是详细的集成步骤:

前置准备

  • 在Google Cloud控制台创建项目,启用Cloud文档AI API,生成服务账号密钥(JSON格式),注意:绝对不能在前端代码中暴露该密钥,必须通过后端服务中转调用API。
  • 准备好文档AI处理器:在控制台创建对应的文档处理器(比如OCR、表单解析等),记录下项目ID、处理器所在区域、处理器ID。

步骤1:搭建后端中转服务(核心)

这里以Node.js + Express为例,使用Google官方的文档AI SDK来封装接口:

// 后端服务示例(Node.js + Express)
const express = require('express');
const { DocumentProcessorServiceClient } = require('@google-cloud/documentai').v1;
const cors = require('cors');
const app = express();

// 配置跨域,允许React前端请求
app.use(cors());
// 解析JSON请求,设置文件大小上限
app.use(express.json({ limit: '50mb' }));

// 初始化文档AI客户端,传入服务账号密钥
const client = new DocumentProcessorServiceClient({
  keyFilename: './path/to/your/service-account-key.json'
});

// 定义文档分析接口
app.post('/api/analyze-document', async (req, res) => {
  try {
    const { projectId, location, processorId, fileContent } = req.body;
    // 构造处理器路径
    const processorPath = client.processorPath(projectId, location, processorId);

    const request = {
      name: processorPath,
      rawDocument: {
        content: fileContent,
        mimeType: 'application/pdf' // 根据实际文件类型调整,比如image/png、image/jpeg
      }
    };

    // 调用文档AI API
    const [result] = await client.processDocument(request);
    res.json(result);
  } catch (error) {
    console.error('文档分析出错:', error);
    res.status(500).json({ message: '文档分析失败,请检查后端配置' });
  }
});

// 启动后端服务
const PORT = 3001;
app.listen(PORT, () => {
  console.log(`后端服务运行在 http://localhost:${PORT}`);
});

步骤2:React前端实现

前端负责文件上传、将文件转为Base64格式,然后调用后端的中转接口:

  1. 安装依赖:
npm install axios
  1. 编写React组件:
import { useState } from 'react';
import axios from 'axios';

const DocumentAIAnalyzer = () => {
  const [selectedFile, setSelectedFile] = useState(null);
  const [analysisResult, setAnalysisResult] = useState(null);
  const [errorMsg, setErrorMsg] = useState('');

  const handleFileSelect = (e) => {
    setSelectedFile(e.target.files[0]);
    setErrorMsg('');
    setAnalysisResult(null);
  };

  const handleAnalyze = async (e) => {
    e.preventDefault();
    if (!selectedFile) {
      setErrorMsg('请选择要分析的文件');
      return;
    }

    // 将文件转为Base64格式
    const reader = new FileReader();
    reader.onload = async () => {
      try {
        // 去掉Base64前缀,只保留内容部分
        const fileContent = reader.result.split(',')[1];
        const response = await axios.post('http://localhost:3001/api/analyze-document', {
          projectId: '你的Google Cloud项目ID',
          location: 'us', // 处理器所在区域,比如us、eu、asia-east1
          processorId: '你的文档AI处理器ID',
          fileContent
        });
        setAnalysisResult(response.data);
      } catch (err) {
        setErrorMsg('分析失败,请检查后端服务是否正常运行');
      }
    };
    reader.readAsDataURL(selectedFile);
  };

  return (
    <div className="document-ai-tool">
      <h2>文档AI分析工具</h2>
      <form onSubmit={handleAnalyze}>
        <input
          type="file"
          accept=".pdf,.png,.jpg,.jpeg"
          onChange={handleFileSelect}
        />
        <button type="submit" disabled={!selectedFile}>
          开始分析
        </button>
      </form>
      {errorMsg && <p className="error">{errorMsg}</p>}
      {analysisResult && (
        <div className="result">
          <h3>分析结果</h3>
          <pre>{JSON.stringify(analysisResult, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default DocumentAIAnalyzer;

关键注意事项

  • 安全优先:永远不要在React代码中直接写入服务账号密钥,所有API请求必须通过后端中转,防止密钥泄露导致的账户被盗用。
  • 文件限制:Cloud文档AI对文件大小和格式有要求,比如PDF文件不超过200MB,图片文件不超过10MB,需确保上传文件符合要求。
  • 区域一致性:后端调用时指定的location参数必须和处理器所在的区域完全一致,否则会出现接口调用失败的情况。
  • 官方参考:可参考Google Cloud文档AI的REST API中文文档,里面包含了所有接口的参数说明和请求示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:22:49