ImageOption.cs 19 KB

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