# General Translation Platform: uploadSourceFiles
URL: https://generaltranslation.com/zh/docs/platform/core/reference/gt-class-methods/translation/upload-source-files.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 在将翻译加入队列之前，先将源文件上传到项目。uploadSourceFiles 的 API 参考。

将源文件上传到 General Translation platform 进行翻译处理。这通常是文件翻译工作流的第一步，需先完成这一步，再设置项目或将翻译任务加入队列。

## 概览 [#overview]

调用 `uploadSourceFiles`，传入文件数组以及用于设置源区域设置的选项对象。该方法会返回已上传的文件引用，供你在后续步骤中使用。

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

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

签名：

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

*注意：`uploadSourceFiles` 要求在 GT 实例上配置 `apiKey` (或 `devApiKey`) 和 `projectId`。*

## 工作原理 [#how-it-works]

* **文件编码。** 文本内容会自动进行 base64 编码，以确保传输安全。二进制 `LOTTIE` 内容必须已进行 base64 编码。
* **文件引用。** 返回的文件引用 (包括 `fileId`、`versionId` 和 `branchId`) 是后续操作的必需输入。
* **典型工作流。** `uploadSourceFiles` 是文件流水线的入口文件：先上传源文件，然后依次执行 [`setupProject`](/docs/platform/core/reference/gt-class-methods/translation/setup-project) → [`enqueueFiles`](/docs/platform/core/reference/gt-class-methods/translation/enqueue-files) → [`queryFileData`](/docs/platform/core/reference/gt-class-methods/translation/query-file-data) → [`downloadFileBatch`](/docs/platform/core/reference/gt-class-methods/translation/download-file-batch)。

## 参数 [#parameters]

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

### `files`

**类型** `{ source: FileUpload }[]` · **必填**

要上传的源文件。每个条目都会在 `source` 键下封装一个 `FileUpload`：

| 字段                   | 描述                                                                                                                                                | 类型                                                              | 可选 |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | -- |
| `content`            | 原始文本内容，或用于 `LOTTIE` 的 base64 编码二进制内容。                                                                                                             | `string`                                                        | 否  |
| `fileName`           | 唯一的文件标识符，通常是文件路径加文件名。                                                                                                                             | `string`                                                        | 否  |
| `fileFormat`         | 文件格式。                                                                                                                                             | [`FileFormat`](/docs/platform/core/reference/types/file-format) | 否  |
| `transformFormat`    | 共享的 `FileUpload` 类型接受该字段，但此方法不会发送它。请在传递给 [`enqueueFiles`](/docs/platform/core/reference/gt-class-methods/translation/enqueue-files) 的文件引用上设置输出格式。 | [`FileFormat`](/docs/platform/core/reference/types/file-format) | 是  |
| `dataFormat`         | 文件内数据的格式 (`ICU`、`I18NEXT`、`JSX` 或 `STRING`) 。                                                                                                     | [`DataFormat`](/docs/platform/core/reference/types/data-format) | 是  |
| `locale`             | 源文件内容的区域设置。                                                                                                                                       | `string`                                                        | 否  |
| `branchId`           | 文件要上传到的分支。省略时使用默认分支。                                                                                                                              | `string`                                                        | 是  |
| `incomingBranchId`   | 分支感知的翻译跟踪所使用的传入分支。                                                                                                                                | `string`                                                        | 是  |
| `checkedOutBranchId` | 分支感知的翻译跟踪所使用的已检出分支。                                                                                                                               | `string`                                                        | 是  |
| `formatMetadata`     | 与源文件一同存储的格式专用元数据。                                                                                                                                 | `GTJsonFormatMetadata \| FormatMetadata`                        | 是  |
| `versionId`          | 版本 ID，用于高级用例。                                                                                                                                     | `string`                                                        | 是  |
| `fileId`             | 文件 ID，用于高级用例。                                                                                                                                     | `string`                                                        | 是  |

### `options`

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

上传配置如下：

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

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

## 返回值 [#returns]

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

最终会得到一个 `UploadFilesResponse`，其中包含已上传的文件引用和摘要：

```typescript
type UploadFilesResponse = {
  uploadedFiles: FileReference[]; // 后续操作的引用
  count: number; // 成功上传的文件数量
  message: string; // API 返回的状态消息
};
```

每个 `FileReference` 的结构如下：

```typescript
type FileReference = {
  fileId: string;
  versionId: string;
  branchId: string; // 对于默认分支，当前 API 可能会省略该字段
  fileName: string;
  fileFormat: FileFormat;
  transformFormat?: FileFormat; // 此上传方法不会填充该字段
  dataFormat?: DataFormat;
};
```

该 library 类型将 `branchId` 声明为必填，但当前 API 在选择默认分支时可以省略它。它也不会填充 `transformFormat`；如果需要进行格式转换，请在将引用传递给 [`enqueueFiles`](/docs/platform/core/reference/gt-class-methods/translation/enqueue-files) 之前设置该字段。

## 示例 [#examples]

```typescript
// 基本用法：上传 JSON 翻译文件
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',
    },
  },
  {
    source: {
      content: fs.readFileSync('./locales/en/navigation.json', 'utf8'),
      fileName: 'navigation.json',
      fileFormat: 'JSON' as const,
      locale: 'en',
    },
  },
];

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

console.log(`Uploaded ${result.count} files`);
result.uploadedFiles.forEach((file) => {
  console.log(`  ${file.fileName}: ${file.fileId} (branch: ${file.branchId})`);
});
```

```typescript
// 显式指定数据格式
const files = [
  {
    source: {
      content: '{"welcome": "Welcome, {name}!"}',
      fileName: 'messages.json',
      fileFormat: 'JSON' as const,
      dataFormat: 'ICU' as const, // ICU 消息格式
      locale: 'en',
    },
  },
  {
    source: {
      content: '{"greeting": "Hello {{name}}"}',
      fileName: 'i18next.json',
      fileFormat: 'JSON' as const,
      dataFormat: 'I18NEXT' as const,
      locale: 'en',
    },
  },
];

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

```typescript
// 批量上传并处理错误
import { glob } from 'glob';
import path from 'path';

async function uploadAllJsonFiles() {
  try {
    // 查找所有 JSON 文件
    const jsonPaths = await glob('./locales/en/**/*.json');

    const files = jsonPaths.map((filePath) => ({
      source: {
        content: fs.readFileSync(filePath, 'utf8'),
        fileName: path.relative('./locales/en', filePath),
        fileFormat: 'JSON' as const,
        locale: 'en',
      },
    }));

    console.log(`Uploading ${files.length} files...`);

    const result = await gt.uploadSourceFiles(files, {
      sourceLocale: 'en',
      timeout: 60000, // 大文件上传超时时间为 60 秒
    });

    if (result.count !== files.length) {
      console.warn(`Expected ${files.length} files, but only ${result.count} uploaded`);
    }

    return result.uploadedFiles;
  } catch (error) {
    console.error('Upload failed:', error);
    throw error;
  }
}

const uploadedFiles = await uploadAllJsonFiles();
```

## 注意事项 [#notes]

* 文本内容会自动进行 Base64 编码，以确保传输安全。请将二进制 `LOTTIE` 内容作为经过 Base64 编码的 `.lottie` ZIP 文件传递。
* 文件名应作为唯一标识符，通常包含文件路径。
* 每个文件中的 `locale` 字段应与 `sourceLocale` 选项保持一致。
* 对于大文件或文件数量较多的情况，可能需要增大请求超时时间。
* 此方法返回的 文件引用 是后续操作所必需的，并包含用于支持 分支 版本管理的 `branchId`。
* **支持的格式：** [`FileFormat`](/docs/platform/core/reference/types/file-format)。

## Sitemap

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