GT ClassMethodsTranslation

downloadFileBatch

API 参考:使用 downloadFileBatch 方法在一次请求中下载多个翻译文件

概述

downloadFileBatch 方法可通过一次批量请求下载多个翻译文件。

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

const result = await gt.downloadFileBatch([
  'translation-id-1', 
  'translation-id-2', 
  'translation-id-3'
]);

批量效率: 此方法经过优化,可在一次 API 调用中同时下载多个文件;相较于多次分别调用 downloadTranslatedFile,可降低网络开销并提升性能。

参考资料

参数

名称类型描述
fileIdsstring[]要下载的翻译文件ID数组
options?DownloadFileBatchOptions下载请求的可选配置项

DownloadFileBatchOptions

名称类型说明
timeout?number请求超时时间(毫秒)

返回值

Promise<DownloadFileBatchResult> - 包含下载的文件及其元数据。

type DownloadFileBatchResult = {
  files: File[];
  count: number;
}
属性类型描述
filesFile[]下载所得的文件对象数组
countnumber成功下载的文件数

文件结构

type File = {
  id: string;
  fileName: string;
  data: string;
  metadata: any;
}
属性类型描述
idstring翻译文件 ID
fileNamestring原始文件名
datastring文件内容(Base64 解码后为 UTF-8 字符串)
metadataany其他文件元数据

示例

index.ts
// (1) 创建 GT 实例
const targetLocales = ['es', 'fr', 'de'];
const gt = new GT({
  projectId: 'your-project-id',
  apiKey: 'your-api-key',
});

// (2) 上传文件
const fileUpload = {
  content: fileContents,
  fileName: filePath,
  fileFormat: 'JSON',
  locale: 'en',
};
const files = [ { source: fileUpload } ];
const { uploadedFiles } = await gt.uploadSourceFiles(
  files,
  { sourceLocale: 'en' }
);

// (3) 将文件翻译任务加入队列
const enqueueResult = await gt.enqueueFiles(
  uploadedFiles,
  {
  sourceLocale: 'en',
  targetLocales: targetLocales,
});

// (4) 等待所有翻译完成
let translationIds = [];
const statusQuery = Object.values(enqueueResult.data).flatMap(({fileName, versionId}) => {
  return targetLocales.map((locale) => ({locale, fileName, versionId}));
});
while (true) {
  const status = await gt.checkFileTranslations(statusQuery);
  if (status.translations.length === statusQuery.length) {
    translationIds = status.translations.map(translation => translation.id);
    break;
  }
  await new Promise(resolve => setTimeout(resolve, 1000));
}

// (5) 下载文件
const result = await gt.downloadFileBatch(translationIds);

注意事项

  • 文件 ID 必须是有效的翻译 ID — 请先使用 checkFileTranslations 验证是否已完成
  • 在可能的情况下,返回的文件顺序与请求的 ID 顺序保持一致
  • 批处理中的单个文件下载失败不会导致整个批处理失败

后续步骤

这份指南怎么样?

downloadFileBatch