# General Translation Platform: uploadTranslations
URL: https://generaltranslation.com/zh/docs/platform/core/reference/gt-class-methods/translation/upload-translations.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 上传与源文件对应的现有翻译后的文件。uploadTranslations 的 API 参考。

为项目中已有的源文件上传现有翻译。当你需要迁移已有翻译，或上传经过人工审校的译文，而不是通过翻译服务生成这些翻译时，可使用此功能。

## 概览 [#overview]

调用 `uploadTranslations` 时，传入一个包含翻译上传项的数组和一个选项对象。每个上传项都包含用于标识已上传源文件的完整源内容，以及一个或多个翻译后的文件。

```typescript
const gt = new GT({ apiKey: 'your-api-key', projectId: 'your-project-id' });

const result = await gt.uploadTranslations(files, {
  sourceLocale: 'en',
});
```

签名：

```typescript
uploadTranslations(
  files: { source: FileUpload; translations: FileUpload[] }[],
  options: UploadFilesOptions
): Promise<UploadFilesResponse>
```

*注意：`uploadTranslations` 要求 GT 实例中提供 `apiKey` (或 `devApiKey`) 和 `projectId`。*

## 工作方式 [#how-it-works]

* **已有源文件。** 请先上传源文件。`source` 对象仍然是一个完整的 `FileUpload`，包含内容和区域设置；API 会从这些数据中推导出缺失的 ID，并使用得到的 ID 查找已有的源版本。
* **翻译内容。** `translations` 数组中的每一项都必须包含内容和目标区域设置。

- **文件编码。** 文本内容会自动进行 Base64 编码。二进制 `LOTTIE` 翻译必须已包含经过 Base64 编码的 `.lottie` ZIP 数据。

* **版本控制。** 返回的文件引用包含 `branchId`，可在支持 branch 的情况下用于版本控制。

## 参数 [#parameters]

| 参数                    | 描述             | 类型                                                     | 可选 | 默认值 |
| --------------------- | -------------- | ------------------------------------------------------ | -- | --- |
| [`files`](#files)     | 由源文件及其译文组成的数组。 | `{ source: FileUpload; translations: FileUpload[] }[]` | 否  | —   |
| [`options`](#options) | 上传的配置选项。       | `UploadFilesOptions`                                   | 否  | —   |

### `files`

**Type** `{ source: FileUpload; translations: FileUpload[] }[]` · **Required**

每一项都将一个完整的源文件与其翻译后的文件配对：

```typescript
{
  source: FileUpload; // 源内容及元数据
  translations: FileUpload[]; // 带有内容的翻译后的文件
}
```

`source` 值使用以下 `FileUpload` 字段：

| Field                | Description                                    | Type                                                            | Optional |
| -------------------- | ---------------------------------------------- | --------------------------------------------------------------- | -------- |
| `content`            | 原始源文本；若为 `LOTTIE`，则为 base64 编码的二进制内容。          | `string`                                                        | No       |
| `fileName`           | 与先前上传的源文件相匹配的文件名。                              | `string`                                                        | No       |
| `fileFormat`         | 文件的格式。                                         | [`FileFormat`](/docs/platform/core/reference/types/file-format) | No       |
| `locale`             | 源内容的区域设置。                                      | `string`                                                        | No       |
| `dataFormat`         | 源文件内数据的格式 (`ICU`、`I18NEXT`、`JSX` 或 `STRING`) 。 | [`DataFormat`](/docs/platform/core/reference/types/data-format) | Yes      |
| `formatMetadata`     | 随源描述符一并接受的格式专用元数据；不会更改已有的源记录。                  | `GTJsonFormatMetadata \| FormatMetadata`                        | Yes      |
| `branchId`           | 包含先前上传源文件的分支。省略时使用默认分支。                        | `string`                                                        | Yes      |
| `fileId`             | 源文件的文件 ID。                                     | `string`                                                        | Yes      |
| `versionId`          | 源文件的版本 ID。                                     | `string`                                                        | Yes      |
| `transformFormat`    | `FileUpload` 接受该字段并在本地验证，但此上传端点不会使用。           | [`FileFormat`](/docs/platform/core/reference/types/file-format) | Yes      |
| `incomingBranchId`   | `FileUpload` 接受该字段，但此方法不会发送。                   | `string`                                                        | Yes      |
| `checkedOutBranchId` | `FileUpload` 接受该字段，但此方法不会发送。                   | `string`                                                        | Yes      |

每个翻译 (一个 `FileUpload`) 使用以下字段：

| Field                | Description                                  | Type                                                            | Optional |
| -------------------- | -------------------------------------------- | --------------------------------------------------------------- | -------- |
| `content`            | 原始译文文本；若为 `LOTTIE`，则为 base64 编码的二进制内容。       | `string`                                                        | No       |
| `fileName`           | `FileUpload` 必需字段；存储的翻译使用源文件的文件名。            | `string`                                                        | No       |
| `fileFormat`         | 文件的格式。                                       | [`FileFormat`](/docs/platform/core/reference/types/file-format) | No       |
| `locale`             | 翻译的目标区域设置。                                   | `string`                                                        | No       |
| `dataFormat`         | 译文数据的格式 (`ICU`、`I18NEXT`、`JSX` 或 `STRING`) 。 | [`DataFormat`](/docs/platform/core/reference/types/data-format) | Yes      |
| `fileId`             | 客户端接受并发送，但端点会忽略；翻译继承源文件的文件 ID。               | `string`                                                        | Yes      |
| `versionId`          | 客户端接受并发送，但端点会忽略；翻译继承源文件的版本 ID。               | `string`                                                        | Yes      |
| `branchId`           | 客户端接受并发送，但端点会忽略；翻译继承源文件所在的分支。                | `string`                                                        | Yes      |
| `transformFormat`    | `FileUpload` 接受该字段，但此方法不会发送。                 | [`FileFormat`](/docs/platform/core/reference/types/file-format) | Yes      |
| `formatMetadata`     | `FileUpload` 接受该字段，但此方法不会发送。                 | `GTJsonFormatMetadata \| FormatMetadata`                        | Yes      |
| `incomingBranchId`   | `FileUpload` 接受该字段，但此方法不会发送。                 | `string`                                                        | Yes      |
| `checkedOutBranchId` | `FileUpload` 接受该字段，但此方法不会发送。                 | `string`                                                        | Yes      |

### `options`

**类型** `UploadFilesOptions` · **必填**

上传配置：

| 字段              | 描述                                                                                                                              | 类型       | 可选 |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------- | -- |
| `sourceLocale`  | 请求的源区域设置。若与项目的默认区域设置不同，还会更新项目的默认区域设置。                                                                                           | `string` | 否  |
| `modelProvider` | 共享选项类型接受该字段，但此上传方法不会发送它。请改为在 [`enqueueFiles`](/docs/platform/core/reference/gt-class-methods/translation/enqueue-files) 上设置提供商。 | `string` | 是  |
| `timeout`       | 请求超时时间 (毫秒) 。                                                                                                                   | `number` | 是  |

*注意：`branchId` 不是上传选项。它是每个文件对象上的字段，而不是 `UploadFilesOptions` 的一部分。*

## 返回 [#returns]

**类型** `Promise<UploadFilesResponse>`

会解析为一个 `UploadFilesResponse`，其中包含已上传的文件引用和摘要：

```typescript
type UploadFilesResponse = {
  uploadedFiles: FileReference[]; // 已上传的文件引用
  count: number; // 成功上传的文件数量
  message: string; // 来自 API 的状态消息
};
```

## 示例 [#examples]

```typescript
// 基本用法：为之前已上传的源文件上传翻译
import { GT } from 'generaltranslation';
import fs from 'fs';

const gt = new GT({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
});

const files = [
  {
    // 完全相同的源文件必须已经上传过。
    source: {
      content: fs.readFileSync('./locales/en/common.json', 'utf8'),
      fileName: 'common.json',
      fileFormat: 'JSON' as const,
      locale: 'en',
    },
    translations: [
      {
        content: fs.readFileSync('./locales/es/common.json', 'utf8'),
        fileName: 'common.json',
        fileFormat: 'JSON' as const,
        locale: 'es',
      },
      {
        content: fs.readFileSync('./locales/fr/common.json', 'utf8'),
        fileName: 'common.json',
        fileFormat: 'JSON' as const,
        locale: 'fr',
      },
    ],
  },
];

const result = await gt.uploadTranslations(files, {
  sourceLocale: 'en',
});

console.log(`Uploaded ${result.count} translation files`);
```

```typescript
// 完整工作流：上传源文件，然后上传对应的翻译
import { GT } from 'generaltranslation';
import fs from 'fs';

const gt = new GT({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
});

// 步骤 1：上传源文件
const sourceFiles = [
  {
    source: {
      content: fs.readFileSync('./locales/en/messages.json', 'utf8'),
      fileName: 'messages.json',
      fileFormat: 'JSON' as const,
      locale: 'en',
    },
  },
];

const { uploadedFiles } = await gt.uploadSourceFiles(sourceFiles, {
  sourceLocale: 'en',
});

// 步骤 2：上传现有翻译
const translationFiles = [
  {
    source: {
      content: sourceFiles[0].source.content,
      fileName: uploadedFiles[0].fileName,
      fileFormat: uploadedFiles[0].fileFormat,
      locale: sourceFiles[0].source.locale,
      fileId: uploadedFiles[0].fileId,
      versionId: uploadedFiles[0].versionId,
    },
    translations: [
      {
        content: fs.readFileSync('./locales/es/messages.json', 'utf8'),
        fileName: 'messages.json',
        fileFormat: 'JSON' as const,
        locale: 'es',
      },
      {
        content: fs.readFileSync('./locales/de/messages.json', 'utf8'),
        fileName: 'messages.json',
        fileFormat: 'JSON' as const,
        locale: 'de',
      },
    ],
  },
];

const translationResult = await gt.uploadTranslations(translationFiles, {
  sourceLocale: 'en',
});

console.log(`Uploaded ${translationResult.count} translations`);
```

```typescript
// 批量上传多个源文件的翻译
import fs from 'node:fs';
import { GT } from 'generaltranslation';
import type { FileUpload } from 'generaltranslation/types';

const gt = new GT({
  apiKey: 'your-api-key',
  projectId: 'your-project-id',
});

async function uploadAllTranslations(
  sourceFiles: FileUpload[],
  targetLocales: string[]
) {
  const files = sourceFiles.map((source) => ({
    source,
    translations: targetLocales
      .map((locale) => {
        const translationPath = `./locales/${locale}/${source.fileName}`;
        try {
          return {
            content: fs.readFileSync(translationPath, 'utf8'),
            fileName: source.fileName,
            fileFormat: source.fileFormat,
            locale,
          };
        } catch {
          // 该区域设置不存在对应的翻译文件
          return null;
        }
      })
      .filter((file): file is FileUpload => file !== null),
  }));

  const result = await gt.uploadTranslations(files, {
    sourceLocale: 'en',
    timeout: 60000,
  });

  return result;
}
```

## 注意事项 [#notes]

* 每个 `entry` 中的 `source` 对象必须包含内容、file name、文件格式和区域设置。
* 该对象所标识的 源版本 必须已存在于项目中。
* `translations` array 中的每条翻译都必须包含内容和目标区域设置。
* 此方法适用于迁移现有翻译，或上传经过人工审校的翻译。
* 文件引用 包含 `branchId`，用于支持 分支 的版本控制。

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
