GT ClassMethodsTranslation
downloadFileBatch
downloadFileBatch 方法的 API 参考:在单个请求中下载多个翻译文件
概述
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'
]);批量效率:
与多次单独调用 downloadTranslatedFile 相比,此方法针对在一次 API 调用中下载多个文件进行了优化,可减少网络开销并提升性能。
参考资料
参数
| 名称 | 类型 | 描述 |
|---|---|---|
fileIds | string[] | 要下载的翻译文件 ID 数组 |
options? | DownloadFileBatchOptions | 下载请求的可选配置 |
DownloadFileBatchOptions
| 名称 | 类型 | 说明 |
|---|---|---|
timeout? | number | 请求超时时间(毫秒) |
返回
Promise<DownloadFileBatchResult> - 包含已下载的文件和元数据。
type DownloadFileBatchResult = {
files: File[];
count: number;
}| 属性 | 类型 | 说明 |
|---|---|---|
files | File[] | 已下载文件对象数组 |
count | number | 成功下载的文件数量 |
文件结构
type File = {
id: string;
fileName: string;
data: string;
metadata: any;
}| 属性 | 类型 | 说明 |
|---|---|---|
id | string | 翻译文件 ID |
fileName | string | 原始文件名 |
data | string | 文件内容(Base64 解码后的 UTF-8 字符串) |
metadata | any | 其他文件元数据 |
示例
// (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 顺序一致
- 批量中单个文件的下载失败不会导致整个批量失败
后续步骤
- 参见
downloadTranslatedFile,下载单个文件 - 参见
checkFileTranslations,验证文件是否已准备就绪可供下载 - 参见
enqueueFiles,启动翻译任务 - 参见
fetchTranslations,获取翻译元数据
本指南如何?