ImageOption.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using com.hnshituo.core.webapp.vo;
  2. using ServiceStack.Redis;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Drawing;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Security;
  12. using System.Reflection;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace CarLocalMeter
  18. {
  19. public class ImageOption
  20. {
  21. Log lg = Log.GetInstance();
  22. Thread task;
  23. string sPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "imgShort\\";
  24. /// <summary>
  25. /// 启动TFP上传线程
  26. /// </summary>
  27. public void Start()
  28. {
  29. if (task == null)
  30. {
  31. task = new Thread(new ThreadStart(Doworks));
  32. task.Start();
  33. }
  34. }
  35. public void Stop()
  36. {
  37. if (task != null)
  38. {
  39. task.Abort();
  40. task = null;
  41. }
  42. }
  43. private void Doworks()
  44. {
  45. do
  46. {
  47. //能ping通服务器IP的情况下
  48. if (CacleCls.serverFlag)
  49. {
  50. int waitSecs = 10000;
  51. try
  52. {
  53. //每隔10秒获取一次结净数据,若完成了结净,且网络正常,
  54. //则进行数据上传,并得到返回的一次编号、二次编号。然后再删除本地数据并将图片修改名称
  55. //服务端需要注意一个事情,就是极端情况下,若数据上传成功,然后没返回,则下次上传数据的时候,需验证
  56. //是否存在同计量点,同时间,同车号的数据,若存在则直接获取一次、二次计量数据的编号返回
  57. UploadFiles(GetFiles(sPath + "formalImg", ".jpg"));
  58. }
  59. catch (Exception exp)
  60. {
  61. lg.WriteLog(LogType.SystemLog, $"图片压缩上传线程异常:{exp.Message}");
  62. }
  63. finally
  64. {
  65. Thread.Sleep(waitSecs);
  66. }
  67. }
  68. } while (true);
  69. }
  70. /// <summary>
  71. /// actualNos的key为本地计量编号,value为服务端一次计量编号
  72. /// 也就是说在数据进行结净的时候,需返回2个一次计量编号以及传过去取的老计量编号
  73. /// </summary>
  74. /// <param name="actualNos"></param>
  75. public void ZipFiles(Dictionary<string,string> actualNos)
  76. {
  77. try
  78. {
  79. ArrayList UnzipedFiles = GetFiles(sPath + "tempImg", ".jpg");//tmp!
  80. if (UnzipedFiles == null || UnzipedFiles.Count == 0) return;
  81. bool flag = false;
  82. string jpgFile = "";
  83. foreach (string fn in UnzipedFiles)
  84. {
  85. if (string.IsNullOrEmpty(fn)) continue;
  86. if (!File.Exists(fn)) continue;
  87. //如果带tempImg则说明没有压缩过,需要压缩
  88. if (fn.Contains("_tempImg"))
  89. {
  90. flag = false;
  91. jpgFile = fn.Replace("_tempImg", "");
  92. foreach (KeyValuePair<string, string> kvp in actualNos)
  93. {
  94. if (fn.Contains(kvp.Key))
  95. {
  96. jpgFile.Replace(kvp.Key, kvp.Value);
  97. flag = true;
  98. break;
  99. }
  100. }
  101. if (flag)
  102. {
  103. Image img = ImageZip.BytesToBitmap(ImageZip.ZipImageByte(fn));
  104. if (fn.Contains("_2.jpg")) //fn.Contains("_1.jpg") ||
  105. {
  106. ImageZip.CompressionImage(img, jpgFile.Replace("tempImg", "formalImg"), AppConfigCache.imgMass > 100 ? 100 : AppConfigCache.imgMass);
  107. }
  108. else
  109. {
  110. ImageZip.CompressionImage(img, jpgFile.Replace("tempImg", "formalImg"), AppConfigCache.imgMass2 > 100 ? 100 : AppConfigCache.imgMass2);
  111. }
  112. File.Delete(fn);//删除临时目录数据
  113. }
  114. else
  115. {
  116. //将文件移送到bakImg文件夹
  117. File.Move(fn, fn.Replace("tempImg", "bakImg"));
  118. }
  119. }
  120. }
  121. }
  122. catch (Exception ex)
  123. {
  124. lg.WriteLog(LogType.SystemLog, $"图片压缩异常:{ex.Message}");
  125. }
  126. }
  127. private void ZipFiles(ArrayList UnzipedFiles)
  128. {
  129. if (UnzipedFiles == null || UnzipedFiles.Count == 0) return;
  130. foreach (string fn in UnzipedFiles)
  131. {
  132. if (string.IsNullOrEmpty(fn)) continue;
  133. if (!File.Exists(fn)) continue;
  134. //如果带tempImg则说明没有压缩过,需要压缩
  135. if (fn.Contains("tempImg"))
  136. {
  137. string jpgFile = fn.Replace("_tempImg", "");
  138. Image img = ImageZip.BytesToBitmap(ImageZip.ZipImageByte(fn));
  139. if (fn.Contains("_2.jpg")) //fn.Contains("_1.jpg") ||
  140. {
  141. ImageZip.CompressionImage(img, jpgFile, AppConfigCache.imgMass > 100 ? 100 : AppConfigCache.imgMass);
  142. }
  143. else
  144. {
  145. ImageZip.CompressionImage(img, jpgFile, AppConfigCache.imgMass2 > 100 ? 100 : AppConfigCache.imgMass2);
  146. }
  147. File.Delete(fn);//删除临时目录数据
  148. }
  149. }
  150. }
  151. public ArrayList GetFiles(string _dirPath, string extensionName)
  152. {
  153. ArrayList files = new ArrayList();
  154. if (!Directory.Exists(_dirPath)) return null;
  155. DirectoryInfo theFolder = new DirectoryInfo(_dirPath);
  156. FileInfo[] fileinfos = theFolder.GetFiles("*" + extensionName);
  157. if (fileinfos != null && fileinfos.Count() > 0)
  158. {
  159. foreach (FileInfo fi in fileinfos)
  160. {
  161. files.Add(fi.FullName);
  162. }
  163. }
  164. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  165. if (dirInfos != null && dirInfos.Count() > 0)
  166. {
  167. foreach (DirectoryInfo di in dirInfos)
  168. {
  169. files.AddRange(GetFiles(di.FullName, extensionName));
  170. }
  171. }
  172. return files;
  173. }
  174. // 后台刷FTP线程调用
  175. private void UploadFiles(ArrayList files)
  176. {
  177. string localpath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"imgShort\formalImg\"));
  178. foreach (string _filepath in files)
  179. {
  180. try
  181. {
  182. // 临时文件不上传
  183. if (!_filepath.Contains("_temp"))
  184. {
  185. string ftpdir = Path.Combine(AppConfigCache.fpath, DateTime.Now.ToString("yyyy-MM-dd"));
  186. //验证文件名是否合法
  187. string filename = Path.GetFileName(_filepath);
  188. //filename : 计量作业编号_序号.jpg 计量作业编号:计量点编号+年月日时分秒
  189. MeterWorkImage ci = ParseFileName(filename, ftpdir.Replace("upload", "download"));
  190. if (ci == null) continue;
  191. // 上传文件
  192. UploadRequest(ftpdir, localpath + filename);
  193. //存储计量数据的时候,实际上是先将计量数据及图片路径
  194. MeterWorkImageService service = new MeterWorkImageService();
  195. RESTfulResult<string> rm = service.doSaveWf(ci); //db.doOption<string>("MeterWorkImageService", "doSaveWf", new object[] { ci }, 1);
  196. if (rm.Succeed)
  197. {
  198. WriteLog(string.Format("更新图片记录[{0}]:{1}", ci.actualFirstNo, filename));
  199. File.Delete(_filepath);
  200. }
  201. else
  202. {
  203. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", ci.actualFirstNo, filename));
  204. }
  205. //
  206. }
  207. }
  208. catch (Exception exp)
  209. {
  210. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", _filepath, exp.Message));
  211. }
  212. }
  213. }
  214. private void RemoveRedundantDir(string _path, int deep)
  215. {
  216. DirectoryInfo theFolder = new DirectoryInfo(_path);
  217. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  218. if (dirInfos != null && dirInfos.Count() > 0)
  219. {
  220. foreach (DirectoryInfo di in dirInfos)
  221. {
  222. RemoveRedundantDir(di.FullName, deep + 1);
  223. }
  224. }
  225. try
  226. {
  227. if (deep == 0) return;
  228. FileInfo[] fileinfos = theFolder.GetFiles();
  229. if (fileinfos == null || fileinfos.Count() == 0)
  230. {
  231. DateTime dt;
  232. if (DateTime.TryParseExact(theFolder.Name, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
  233. {
  234. if (TimeSpan.FromTicks(DateTime.Today.Ticks).Subtract(TimeSpan.FromTicks(dt.Date.Ticks)).TotalDays > 1)
  235. {
  236. Directory.Delete(_path);
  237. }
  238. }
  239. }
  240. }
  241. catch { }
  242. }
  243. /// <summary>
  244. /// 验证图片名称
  245. /// </summary>
  246. /// <param name="filename">计量点编号_作业编号_序号.jpg</param>
  247. /// <param name="ftpdir"></param>
  248. /// <returns></returns>
  249. private MeterWorkImage ParseFileName(string filename, string ftpdir)
  250. {
  251. MeterWorkImage ci = new MeterWorkImage();
  252. filename = Path.GetFileName(filename);
  253. string[] segs = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
  254. if (segs == null || segs.Count() < 3)
  255. {
  256. WriteLog("文件名不符合要求! (3段命名):" + filename);
  257. return null;
  258. }
  259. int seq;
  260. //int icar_seq = 0;
  261. //int.TryParse(car_seq, out icar_seq);
  262. string[] seqs = segs[2].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  263. if (seqs == null || seqs.Count() == 0 || !int.TryParse(seqs[0], out seq))
  264. {
  265. WriteLog("文件名不符合要求! (序号不正确):" + filename);
  266. return null;
  267. }
  268. string fullfilename = ftpdir + "/" + filename;
  269. if (fullfilename.Substring(0, 8) == "https://")
  270. {
  271. fullfilename = fullfilename.Substring(0, 8) + fullfilename.Substring(8).Replace("//", "/").Replace("//", "/");
  272. }
  273. else if (fullfilename.Substring(0, 7) == "http://")
  274. {
  275. fullfilename = fullfilename.Substring(0, 7) + fullfilename.Substring(7).Replace("//", "/").Replace("//", "/");
  276. }
  277. else
  278. {
  279. fullfilename = fullfilename.Replace("//", "/").Replace("//", "/");
  280. }
  281. PropertyInfo pi = null;
  282. try
  283. {
  284. pi = ci.GetType().GetProperty(string.Format("imageFile{0}", seq));
  285. pi.SetValue(ci, fullfilename.Replace("/pub", ""));
  286. }
  287. catch
  288. {
  289. WriteLog("文件名不符合要求! (序号超出数据库要求):" + fullfilename);
  290. return null;
  291. }
  292. //ci.image_time = DateTime.ParseExact(segs[0].Substring(segs[0].Length - 14, 14), "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
  293. ci.actualFirstNo = segs[1];
  294. return ci;
  295. }
  296. private static void WriteLog(string str)
  297. {
  298. // 20220925 By BourneCao 暂时屏蔽语音播放日志
  299. return;
  300. try
  301. {
  302. string m_szRunPath;
  303. m_szRunPath = System.Environment.CurrentDirectory;
  304. if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
  305. {
  306. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  307. }
  308. string strDate = System.DateTime.Now.ToString("yyyyMMdd");
  309. string strPathFile = m_szRunPath + "\\log\\" + strDate;
  310. if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
  311. {
  312. Directory.CreateDirectory(strPathFile);
  313. }
  314. System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_image_" + strDate + ".log", true);
  315. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  316. tw.WriteLine(str);
  317. tw.WriteLine("\r\n");
  318. tw.Close();
  319. }
  320. catch { }
  321. }
  322. private void UploadRequest(string url, string filePath)
  323. {
  324. // 时间戳,用做boundary
  325. string timeStamp = DateTime.Now.Ticks.ToString("x");
  326. //根据uri创建HttpWebRequest对象
  327. HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
  328. //如果是发送HTTPS请求
  329. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  330. {
  331. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  332. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
  333. | SecurityProtocolType.Tls
  334. | (SecurityProtocolType)0x300 //Tls11
  335. | (SecurityProtocolType)0xC00; //Tls12
  336. oWebrequest = WebRequest.Create(url) as HttpWebRequest;
  337. oWebrequest.ProtocolVersion = HttpVersion.Version11;
  338. }
  339. else
  340. {
  341. oWebrequest = WebRequest.Create(url) as HttpWebRequest;
  342. }
  343. //HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  344. oWebrequest.Method = "POST";
  345. oWebrequest.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  346. oWebrequest.Timeout = 300000; //设置获得响应的超时时间(300秒)
  347. oWebrequest.ContentType = "multipart/form-data; boundary=" + timeStamp;
  348. //文件
  349. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  350. BinaryReader binaryReader = new BinaryReader(fileStream);
  351. //头信息
  352. string boundary = "--" + timeStamp;
  353. string dataFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
  354. string header = string.Format(dataFormat, "file", Path.GetFileName(filePath));
  355. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header);
  356. //结束边界
  357. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n");
  358. long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
  359. oWebrequest.ContentLength = length;//请求内容长度
  360. try
  361. {
  362. //每次上传4k
  363. int bufferLength = 4096;
  364. byte[] buffer = new byte[bufferLength];
  365. //已上传的字节数
  366. long offset = 0;
  367. int size = binaryReader.Read(buffer, 0, bufferLength);
  368. Stream postStream = oWebrequest.GetRequestStream();
  369. //发送请求头部消息
  370. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  371. while (size > 0)
  372. {
  373. postStream.Write(buffer, 0, size);
  374. offset += size;
  375. size = binaryReader.Read(buffer, 0, bufferLength);
  376. }
  377. //添加尾部边界
  378. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  379. postStream.Close();
  380. //获取服务器端的响应
  381. using (HttpWebResponse response = (HttpWebResponse)oWebrequest.GetResponse())
  382. {
  383. Stream receiveStream = response.GetResponseStream();
  384. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  385. string returnValue = readStream.ReadToEnd();
  386. response.Close();
  387. readStream.Close();
  388. }
  389. }
  390. catch (Exception ex)
  391. {
  392. //Debug.WriteLine("文件传输异常: " + ex.Message);
  393. }
  394. finally
  395. {
  396. fileStream.Close();
  397. binaryReader.Close();
  398. }
  399. }
  400. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  401. {
  402. return true; //总是接受
  403. }
  404. }
  405. }