ImageOption.cs 19 KB

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