使用node-fetch调用Azure文档翻译API遇ContentType格式错误求助
问题解决与参数说明
错误原因
你遇到的InvalidFormat错误,核心原因是错误地用FormData直接上传文件。Microsoft文档翻译的document:translate端点不支持这种请求方式,它要求请求体为JSON格式,指定文件在Azure Blob存储中的路径,而非直接传输文件内容。
参数说明
document参数
这是请求体中的必填字段,用于指定源文件的读取路径和翻译后文件的写入路径,两者都必须是带对应权限的Azure Blob SAS URL:
sourceUrl:带读取权限的SAS URL,API将从这里获取要翻译的源文件targetUrl:带写入权限的SAS URL,API会把翻译后的文件写入这个位置
type查询参数
可选参数,用于手动指定文件格式(如pdf、docx)。如果API能自动识别文件格式,可省略该参数;若自动识别失败,手动指定能避免格式相关错误。
修正后的代码示例
import fetch from 'node-fetch' async function run() { try { const headers = new Headers({ 'Ocp-Apim-Subscription-Key': 'xxx', 'Content-Type': 'application/json' }); // 替换为你的Azure Blob SAS URL const requestBody = { document: { sourceUrl: 'https://your-storage-account.blob.core.windows.net/source/test.pdf?your-read-sas-token', targetUrl: 'https://your-storage-account.blob.core.windows.net/target/test_fr.pdf?your-write-sas-token' } }; const response = await fetch( `https://xxx.cognitiveservices.azure.com/translator/document:translate?targetLanguage=fr&api-version=2024-05-01`, { method: 'POST', headers, body: JSON.stringify(requestBody) } ) const result = await response.json(); console.log(result); } catch (error) { console.error(error) } } run()
为什么需要存储路径而非FormData
文档翻译API针对大文件设计,采用异步处理模式。直接通过请求体上传文件会受限于HTTP请求大小,而使用Azure Blob存储路径,API可以直接从存储服务读取文件、处理后写入目标位置,更适合大文件或批量翻译场景。
内容的提问来源于stack exchange,提问作者Ajouve
相关产品推荐
相关产品推荐

