ImageOption.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 + "tempImg", ".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 + "tempImg", ".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.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. files.Add(fi.FullName);
  171. }
  172. }
  173. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  174. if (dirInfos != null && dirInfos.Count() > 0)
  175. {
  176. foreach (DirectoryInfo di in dirInfos)
  177. {
  178. files.AddRange(GetFiles(di.FullName, extensionName));
  179. }
  180. }
  181. return files;
  182. }
  183. // 后台刷FTP线程调用
  184. private void UploadFiles(ArrayList files)
  185. {
  186. string localpath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"imgShort\formalImg\"));
  187. foreach (string _filepath in files)
  188. {
  189. try
  190. {
  191. // 临时文件不上传
  192. if (!_filepath.Contains("_temp"))
  193. {
  194. string ftpdir = Path.Combine(AppConfigCache.fpath, DateTime.Now.ToString("yyyy-MM-dd"));
  195. //验证文件名是否合法
  196. string filename = Path.GetFileName(_filepath);
  197. //filename : 计量作业编号_序号.jpg 计量作业编号:计量点编号+年月日时分秒
  198. MeterWorkImage ci = ParseFileName(filename, ftpdir.Replace("upload", "download"));
  199. if (ci == null) continue;
  200. // 上传文件
  201. UploadRequest(ftpdir, localpath + filename);
  202. //存储计量数据的时候,实际上是先将计量数据及图片路径
  203. MeterWorkImageService service = new MeterWorkImageService();
  204. RESTfulResult<string> rm = service.doSaveWf(ci); //db.doOption<string>("MeterWorkImageService", "doSaveWf", new object[] { ci }, 1);
  205. if (rm.Succeed)
  206. {
  207. WriteLog(string.Format("更新图片记录[{0}]:{1}", ci.actualFirstNo, filename));
  208. File.Delete(_filepath);
  209. }
  210. else
  211. {
  212. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", ci.actualFirstNo, filename));
  213. }
  214. //
  215. }
  216. }
  217. catch (Exception exp)
  218. {
  219. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", _filepath, exp.Message));
  220. }
  221. }
  222. }
  223. private void RemoveRedundantDir(string _path, int deep)
  224. {
  225. DirectoryInfo theFolder = new DirectoryInfo(_path);
  226. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  227. if (dirInfos != null && dirInfos.Count() > 0)
  228. {
  229. foreach (DirectoryInfo di in dirInfos)
  230. {
  231. RemoveRedundantDir(di.FullName, deep + 1);
  232. }
  233. }
  234. try
  235. {
  236. if (deep == 0) return;
  237. FileInfo[] fileinfos = theFolder.GetFiles();
  238. if (fileinfos == null || fileinfos.Count() == 0)
  239. {
  240. DateTime dt;
  241. if (DateTime.TryParseExact(theFolder.Name, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
  242. {
  243. if (TimeSpan.FromTicks(DateTime.Today.Ticks).Subtract(TimeSpan.FromTicks(dt.Date.Ticks)).TotalDays > 1)
  244. {
  245. Directory.Delete(_path);
  246. }
  247. }
  248. }
  249. }
  250. catch { }
  251. }
  252. /// <summary>
  253. /// 验证图片名称
  254. /// </summary>
  255. /// <param name="filename">计量点编号_作业编号_序号.jpg</param>
  256. /// <param name="ftpdir"></param>
  257. /// <returns></returns>
  258. private MeterWorkImage ParseFileName(string filename, string ftpdir)
  259. {
  260. MeterWorkImage ci = new MeterWorkImage();
  261. filename = Path.GetFileName(filename);
  262. string[] segs = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
  263. if (segs == null || segs.Count() < 3)
  264. {
  265. WriteLog("文件名不符合要求! (3段命名):" + filename);
  266. return null;
  267. }
  268. int seq;
  269. //int icar_seq = 0;
  270. //int.TryParse(car_seq, out icar_seq);
  271. string[] seqs = segs[2].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  272. if (seqs == null || seqs.Count() == 0 || !int.TryParse(seqs[0], out seq))
  273. {
  274. WriteLog("文件名不符合要求! (序号不正确):" + filename);
  275. return null;
  276. }
  277. string fullfilename = ftpdir + "/" + filename;
  278. if (fullfilename.Substring(0, 8) == "https://")
  279. {
  280. fullfilename = fullfilename.Substring(0, 8) + fullfilename.Substring(8).Replace("//", "/").Replace("//", "/");
  281. }
  282. else if (fullfilename.Substring(0, 7) == "http://")
  283. {
  284. fullfilename = fullfilename.Substring(0, 7) + fullfilename.Substring(7).Replace("//", "/").Replace("//", "/");
  285. }
  286. else
  287. {
  288. fullfilename = fullfilename.Replace("//", "/").Replace("//", "/");
  289. }
  290. PropertyInfo pi = null;
  291. try
  292. {
  293. pi = ci.GetType().GetProperty(string.Format("imageFile{0}", seq));
  294. pi.SetValue(ci, fullfilename.Replace("/pub", ""));
  295. }
  296. catch
  297. {
  298. WriteLog("文件名不符合要求! (序号超出数据库要求):" + fullfilename);
  299. return null;
  300. }
  301. //ci.image_time = DateTime.ParseExact(segs[0].Substring(segs[0].Length - 14, 14), "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
  302. ci.actualFirstNo = segs[1];
  303. return ci;
  304. }
  305. private static void WriteLog(string str)
  306. {
  307. // 20220925 By BourneCao 暂时屏蔽语音播放日志
  308. return;
  309. try
  310. {
  311. string m_szRunPath;
  312. m_szRunPath = System.Environment.CurrentDirectory;
  313. if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
  314. {
  315. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  316. }
  317. string strDate = System.DateTime.Now.ToString("yyyyMMdd");
  318. string strPathFile = m_szRunPath + "\\log\\" + strDate;
  319. if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
  320. {
  321. Directory.CreateDirectory(strPathFile);
  322. }
  323. System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_image_" + strDate + ".log", true);
  324. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  325. tw.WriteLine(str);
  326. tw.WriteLine("\r\n");
  327. tw.Close();
  328. }
  329. catch { }
  330. }
  331. private void UploadRequest(string url, string filePath)
  332. {
  333. // 时间戳,用做boundary
  334. string timeStamp = DateTime.Now.Ticks.ToString("x");
  335. //根据uri创建HttpWebRequest对象
  336. HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
  337. //如果是发送HTTPS请求
  338. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  339. {
  340. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  341. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
  342. | SecurityProtocolType.Tls
  343. | (SecurityProtocolType)0x300 //Tls11
  344. | (SecurityProtocolType)0xC00; //Tls12
  345. oWebrequest = WebRequest.Create(url) as HttpWebRequest;
  346. oWebrequest.ProtocolVersion = HttpVersion.Version11;
  347. }
  348. else
  349. {
  350. oWebrequest = WebRequest.Create(url) as HttpWebRequest;
  351. }
  352. //HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  353. oWebrequest.Method = "POST";
  354. oWebrequest.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  355. oWebrequest.Timeout = 300000; //设置获得响应的超时时间(300秒)
  356. oWebrequest.ContentType = "multipart/form-data; boundary=" + timeStamp;
  357. //文件
  358. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  359. BinaryReader binaryReader = new BinaryReader(fileStream);
  360. //头信息
  361. string boundary = "--" + timeStamp;
  362. string dataFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
  363. string header = string.Format(dataFormat, "file", Path.GetFileName(filePath));
  364. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header);
  365. //结束边界
  366. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n");
  367. long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
  368. oWebrequest.ContentLength = length;//请求内容长度
  369. try
  370. {
  371. //每次上传4k
  372. int bufferLength = 4096;
  373. byte[] buffer = new byte[bufferLength];
  374. //已上传的字节数
  375. long offset = 0;
  376. int size = binaryReader.Read(buffer, 0, bufferLength);
  377. Stream postStream = oWebrequest.GetRequestStream();
  378. //发送请求头部消息
  379. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  380. while (size > 0)
  381. {
  382. postStream.Write(buffer, 0, size);
  383. offset += size;
  384. size = binaryReader.Read(buffer, 0, bufferLength);
  385. }
  386. //添加尾部边界
  387. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  388. postStream.Close();
  389. //获取服务器端的响应
  390. using (HttpWebResponse response = (HttpWebResponse)oWebrequest.GetResponse())
  391. {
  392. Stream receiveStream = response.GetResponseStream();
  393. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  394. string returnValue = readStream.ReadToEnd();
  395. response.Close();
  396. readStream.Close();
  397. }
  398. }
  399. catch (Exception ex)
  400. {
  401. //Debug.WriteLine("文件传输异常: " + ex.Message);
  402. }
  403. finally
  404. {
  405. fileStream.Close();
  406. binaryReader.Close();
  407. }
  408. }
  409. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  410. {
  411. return true; //总是接受
  412. }
  413. }
  414. }