GT ClassMethodsTranslation

downloadTranslatedFile

downloadTranslatedFile 方法的 API 参考:下载已完成的翻译文件

概述

downloadTranslatedFile 方法会将单个已翻译文件的内容下载为 UTF-8 编码的字符串。 该方法用于在 General Translation 平台处理完成后获取已完成的译文。

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

const content = await gt.downloadTranslatedFile({
  fileId: 'file-123',
  locale: 'es',
  versionId: 'version-456'
});

翻译状态: 此方法仅适用于已完成的翻译。 在尝试下载之前,请先使用 checkFileTranslations 确认翻译已完成。

参考资料

参数

名称类型描述
fileFileInfo指定要下载文件的文件信息对象
options?DownloadFileOptions下载请求的可选配置

FileInfo 结构

名称类型描述
fileIdstring要下载的文件的唯一标识符
localestring要下载翻译所用的目标 locale
versionId?string文件的可选版本 ID

DownloadFileOptions

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

返回值

Promise<string> - 以 UTF-8 字符串形式提供翻译后的文件内容。

返回的字符串与原始源文件保持相同的格式,且所有可翻译文本均已转换为目标 locale。


示例

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 Promise.all(
  translationIds.map(id => gt.downloadTranslatedFile(id))
);

说明

  • 以 UTF-8 编码的字符串形式获取已下载文件
  • 该文件必须已完成指定 locale 的翻译
  • 若未找到文件,则调用失败

后续步骤

这份指南怎么样?

downloadTranslatedFile