C#实现百度智能云文档翻译 电脑版发表于:2022/12/28 17:52 ## C#实现百度智能云文档翻译 tn2>https://login.bce.baidu.com/?redirect=https%3A%2F%2Fconsole.bce.baidu.com%2Ftools%2F%3F_%3D1672204525069#/api?product=AI&project=%E6%9C%BA%E5%99%A8%E7%BF%BB%E8%AF%91&parent=%E6%96%87%E6%A1%A3%E7%BF%BB%E8%AF%91&api=rpc%2F2.0%2Fmt%2Fv2%2Fdoc-translation%2Fquery&method=post ```csharp namespace BaiduTranslateLibrary { public static class TranslateFunction { public static void TestTranslate() { TranslateConfig translateConfig = new TranslateConfig() { appId = "xxxxx", passWord = "xxxx" }; string filepath = @"C:\Users\cn49ak\Downloads\xxxx.pdf"; var verificationservice = translateConfig.TranslateVerificationService(filepath, "en", "zh"); var translateservice = translateConfig.Translate(verificationservice.fileId, filepath, "en", "zh"); } /// <summary> /// 校验服务 /// </summary> /// <returns></returns> public static PostVerificationResult TranslateVerificationService(this TranslateConfig translateConfig,string filepath, string languageFrom, string languageTo) { string appId = translateConfig.appId, passWord = translateConfig.passWord, randomNum = translateConfig.GetRandomNumber; long timestamp = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; string safeFileName = Path.GetFileName(filepath); // NPOIFileContext.FileRead(filepath); string extension = Path.GetExtension(filepath).Substring(1).ToLower(); string UrlRequest = "https://fanyi-api.baidu.com/api/trans/vip/doctrans?"; string ortherparams = "appid=" + appId + "&from=" + languageFrom + "&to=" + languageTo + "×tamp=" + timestamp + "&type=" + extension +"&"; //+ "&sign=" + md5Sign; string md5Sign = MD5EX.GetMD5HashFromFile(filepath).ToLower(); // 拼接 string md5Sign2 = MD5EX.EncryptString(ortherparams + md5Sign + passWord).ToLower(); string FullRequest = UrlRequest + ortherparams + "sign=" + md5Sign2; string m_postResult = PostFile(FullRequest, filepath); PostVerificationResult m_postResultds = new JavaScriptSerializer().Deserialize<PostVerificationResult>(m_postResult); return m_postResultds; } public static string PostFile(string url, string fileName) { //验证文件是否存在 if (File.Exists(fileName) == false) throw new Exception("发送文件不存在!"); FileInfo file = new FileInfo(fileName); string boundary = "qianle";//分隔符 HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; //构造请求体 byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] byteEnd = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //结束标识 --xxxx-- StringBuilder strContent = new StringBuilder(); strContent .Append("Content-Disposition:form-data;name=\"file\";filename=\"" + file.Name + "\"") .AppendLine() .Append("Content-Type:application/octet-stream") .AppendLine() .AppendLine(); //特别说明,Content-Disposition 前边不能添加换行符号 byte[] byteContent = Encoding.UTF8.GetBytes(strContent.ToString()); byte[] byteFile = File.ReadAllBytes(fileName); //执行发送 req.Method = "POST"; req.ContentType = $"multipart/form-data;charset=utf-8;boundary={boundary}"; //req.UserAgent = UserAgent; req.ContinueTimeout = 20000; var reqStrem = req.GetRequestStream(); reqStrem.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); //文件开始 reqStrem.Write(byteContent, 0, byteContent.Length);//文件信息 reqStrem.Write(byteFile, 0, byteFile.Length);//文件内容 reqStrem.Write(byteEnd, 0, byteEnd.Length); //文件结束 reqStrem.Close(); WebResponse resp = req.GetResponse(); StreamReader sr = new StreamReader(resp.GetResponseStream()); string result = sr.ReadToEnd(); sr.Close(); resp.Close(); return result; } public static PostResult Translate(this TranslateConfig translateConfig, string field,string filepath, string languageFrom, string languageTo,string outPutType = "docx") { string appId = translateConfig.appId, passWord = translateConfig.passWord, randomNum = translateConfig.GetRandomNumber; long timestamp = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; string extension = Path.GetExtension(filepath).Substring(1).ToLower(); string md5Sign = MD5EX.EncryptString(appId + randomNum + passWord).ToLower(); string FullRequest = "https://fanyi-api.baidu.com/api/trans/vip/doctrans?type=" + extension + "&outPutType=" + outPutType + "&fileId=" + field + "×tamp=" + timestamp + "&from=" + languageFrom + "&to=" + languageTo + "&appid=" + appId + "&sign=" + md5Sign; string m_Content = new WebClient().DownloadString(FullRequest); PostResult m_postResult = new JavaScriptSerializer().Deserialize<PostResult>(m_Content); return m_postResult; } public class TranslateConfig { public TranslateConfig() { randomNum = new Random().Next().ToString(); } public string appId { get; set; } public string passWord { get; set; } private string randomNum { get; set; } public string GetRandomNumber => randomNum; } public class PostVerificationResult { public string Error_code { set; get; } public string Error_msg { set; get; } public string From { set; get; } public string To { set; get; } public object data { get; set; } public int charCount { get; set; } public string fileId { get; set; } /// <summary> /// 预算:单位分 /// </summary> public int amount { set; get; } } public class PostResult { public string Error_code { set; get; } public string Error_msg { set; get; } public string From { set; get; } public string To { set; get; } public TranslateContent[] Trans_result { set; get; } } public class TranslateContent { public string Src { set; get; } public string Dst { set; get; } } } } ```