Base64 編碼

將文件檔案傳送至 Document AI API 時,如果檔案大小為 20 MB 以下,您可以線上處理,直接在 RawDocument.content 欄位中傳送資料。輸入檔案為二進位格式,必須先經過編碼,才能傳送至 Document AI。

如果輸入檔案超過線上處理限制,就必須儲存在 Cloud Storage 值區中,才能傳送處理,且不需要編碼。詳情請參閱批次處理說明文件

使用指令列

在 gRPC 要求內,您只需直接寫出二進位資料即可;但是,當提出 REST 要求時,會使用 JSON。JSON 是一種文字格式,不直接支援二進位資料,因此您需要使用 Base64 編碼,將這類二進位資料轉換為文字。

大多數開發環境都含有原生 base64 公用程式,可將二進位編碼為 ASCII 文字資料。如要編碼檔案:

Linux

使用 base64 指令列工具對檔案進行編碼,並使用 -w 0 標記確保不會換行:

base64 INPUT_FILE -w 0 > OUTPUT_FILE

macOS

使用 base64 指令列工具編碼檔案:

base64 -i INPUT_FILE -o OUTPUT_FILE

Windows

使用 Base64.exe 工具編碼檔案:

Base64.exe -e INPUT_FILE > OUTPUT_FILE

PowerShell

使用 Convert.ToBase64String 方法對檔案進行編碼:

[Convert]::ToBase64String([IO.File]::ReadAllBytes("./INPUT_FILE")) > OUTPUT_FILE

建立 JSON 要求檔案,內嵌 base64 編碼資料:

JSON

{
  "skipHumanReview": skipHumanReview,
  "rawDocument": {
    "mimeType": "MIME_TYPE",
    "content": "BASE64_ENCODED_DATA"
  },
  "fieldMask": "FIELD_MASK"
}

使用用戶端程式庫

透過文字編輯器將二進位資料嵌入要求中,既不理想也不切實際。實際上,您會將 base64 編碼的檔案嵌入用戶端程式碼內。所有支援的程式設計語言都擁有適用於 base64 編碼內容的內建機制。

Python

# Import the base64 encoding library.
import base64

# Pass the image data to an encoding function.
def encode_image(image):
    with open(image, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    return encoded_string

Node.js

// Read the file into memory.
var fs = require('fs');
var imageFile = fs.readFileSync('/path/to/file');

// Convert the image data to a Buffer and base64 encode it.
var encoded = Buffer.from(imageFile).toString('base64');

Java

// Import the Base64 encoding library.
import org.apache.commons.codec.binary.Base64;

// Encode the image.
String encodedString = Base64.getEncoder().encodeToString(imageFile.getBytes());

Go

import (
    "bufio"
    "encoding/base64"
    "io"
    "os"
)

// Open image file.
f, _ := os.Open("image.jpg")

// Read entire image into byte slice.
reader := bufio.NewReader(f)
content, _ := io.ReadAll(reader)

// Encode image as base64.
base64.StdEncoding.EncodeToString(content)