ImageControl.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. using Core.Mes.Client.Comm.Format;
  2. using Core.StlMes.Client.LgResMgt.Mcms.entity;
  3. using CoreFS.CA06;
  4. using Newtonsoft.Json;
  5. using Newtonsoft.Json.Serialization;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Drawing;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Text;
  15. using System.Threading;
  16. namespace Core.StlMes.Client.LgResMgt.Mcms
  17. {
  18. /// <summary>
  19. /// 在进入系统后,需开启这个线程用于每10秒上传一次图片到ftp服务器
  20. /// 在退出系统后,需关闭这个线程
  21. /// </summary>
  22. public class ImageControl
  23. {
  24. SFTPHelper ftp_helper;
  25. VSFTPHelper vftp_helper;
  26. Thread task;
  27. string FtpIp { get; set; }
  28. int FtpPort { get; set; }
  29. string Username { get; set; }
  30. string FtpPwd { get; set; }
  31. string Ftptype { get; set; }
  32. string FtpPath { get; set; }
  33. public OpeBase OB { get; set; }
  34. public ImageControl(string ftpIp ,string ftpPort,string username,string ftpPwd ,string ftptype,string path , OpeBase ob)
  35. {
  36. FtpPort = Convert.ToInt32(ftpPort);
  37. FtpIp = ftpIp;
  38. Username = username;
  39. FtpPwd = ftpPwd;
  40. Ftptype = ftptype;
  41. FtpPath = path;
  42. OB = ob;
  43. switch (ftptype)//区别在哪。先确认一下
  44. {
  45. case "0":
  46. ftp_helper = new SFTPHelper(ftpIp, FtpPort, username, ftpPwd);
  47. break;
  48. case "1":
  49. vftp_helper = new VSFTPHelper( ftpIp, username, ftpPwd, path);
  50. break;
  51. }
  52. }
  53. public void Start()
  54. {
  55. if (task == null)
  56. {
  57. task = new Thread(new ThreadStart(Doworks));
  58. task.Start();
  59. }
  60. }
  61. public void Stop()
  62. {
  63. if (task != null)
  64. {
  65. task.Abort();
  66. task = null;
  67. }
  68. }
  69. private void Doworks()
  70. {
  71. do
  72. {
  73. int waitSecs = 10000;
  74. int i = 0;
  75. try
  76. {
  77. string sPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\imgShort\\";
  78. i = 1;
  79. string picPath = Path.Combine(sPath, "tempImg");
  80. i = 2;
  81. ArrayList UnZipedFiles = GetFiles(picPath, ".jpg");//tmp!
  82. i = 3;
  83. //ZipFiles(UnZipedFiles); //2021年3月2日不再进行图片压缩,直接存到正式文件夹formalImg中
  84. i = 4;
  85. //获取正式目录文件进行上传
  86. ArrayList files = GetFiles(sPath + "formalImg", ".jpg");
  87. i = 5;
  88. UploadFiles(files);
  89. i = 6;
  90. //删除正式目录文件
  91. RemoveRedundantDir(Path.Combine(sPath, "formalImg"), 0);
  92. i = 7;
  93. }
  94. catch (Exception exp)
  95. {
  96. WriteLog("ImageControl.Doworks在" + i + "位置异常,异常信息:" + exp.Message);
  97. }
  98. finally
  99. {
  100. Thread.Sleep(waitSecs);
  101. }
  102. } while (true);
  103. }
  104. private void RemoveRedundantDir(string _path, int deep)
  105. {
  106. DirectoryInfo theFolder = new DirectoryInfo(_path);
  107. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  108. if (dirInfos != null && dirInfos.Count() > 0)
  109. {
  110. foreach (DirectoryInfo di in dirInfos)
  111. {
  112. RemoveRedundantDir(di.FullName, deep + 1);
  113. }
  114. }
  115. try
  116. {
  117. if (deep == 0) return;
  118. FileInfo[] fileinfos = theFolder.GetFiles();
  119. if (fileinfos == null || fileinfos.Count() == 0)
  120. {
  121. DateTime dt;
  122. if (DateTime.TryParseExact(theFolder.Name, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
  123. {
  124. if (TimeSpan.FromTicks(DateTime.Today.Ticks).Subtract(TimeSpan.FromTicks(dt.Date.Ticks)).TotalDays > 1)
  125. {
  126. Directory.Delete(_path);
  127. }
  128. }
  129. }
  130. }
  131. catch { }
  132. }
  133. private void ZipFiles(ArrayList UnzipedFiles)
  134. {
  135. ImageZip iz = new ImageZip();
  136. if (UnzipedFiles == null || UnzipedFiles.Count == 0) return;
  137. foreach (string fn in UnzipedFiles)
  138. {
  139. if (string.IsNullOrEmpty(fn)) continue;
  140. if (!File.Exists(fn)) continue;
  141. //临时目录图片压缩后存储与正式目录
  142. string jpgFile = fn.Replace("tempImg", "formalImg");
  143. Image img = ImageZip.BytesToBitmap(ImageZip.ZipImageByte(fn));
  144. if (img != null)
  145. {
  146. //iz.ResourceImage = img;
  147. //压缩图片并保存
  148. //iz.GetReducedImage(AppConfigCache.imgWidth, AppConfigCache.imgHeight).Save(jpgFile);
  149. img.Save(jpgFile);
  150. File.Delete(fn);//删除临时目录数据
  151. }
  152. else
  153. {
  154. iz.ResourceImage = img;
  155. //压缩图片并保存
  156. iz.GetReducedImage(400, 400).Save(jpgFile);
  157. //File.Move(fn, jpgFile);
  158. }
  159. }
  160. }
  161. private ArrayList GetFiles(string _dirPath, string extensionName)
  162. {
  163. ArrayList files = new ArrayList();
  164. if (!Directory.Exists(_dirPath)) return null;
  165. DirectoryInfo theFolder = new DirectoryInfo(_dirPath);
  166. FileInfo[] fileinfos = theFolder.GetFiles("*" + extensionName);
  167. if (fileinfos != null && fileinfos.Count() > 0)
  168. {
  169. foreach (FileInfo fi in fileinfos)
  170. {
  171. files.Add(fi.FullName);
  172. }
  173. }
  174. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  175. if (dirInfos != null && dirInfos.Count() > 0)
  176. {
  177. foreach (DirectoryInfo di in dirInfos)
  178. {
  179. files.AddRange(GetFiles(di.FullName, extensionName));
  180. }
  181. }
  182. return files;
  183. }
  184. // 后台刷FTP线程调用
  185. private void UploadFiles(ArrayList files)
  186. {
  187. if ("0".Equals(Ftptype))
  188. {
  189. if (files == null || files.Count == 0 || ftp_helper == null) return;
  190. }
  191. else
  192. {
  193. if (files == null || files.Count == 0 || vftp_helper == null) return;
  194. }
  195. if (Ftptype == "0")
  196. {
  197. if (!ftp_helper.Connect()) return;
  198. }
  199. string localpath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"imgShort\formalImg\"));
  200. string lastpath = FtpPath;
  201. foreach (string _filepath in files)
  202. {
  203. try
  204. {
  205. //计算ftp相对路径
  206. Uri u1 = new Uri(localpath, UriKind.Absolute);
  207. Uri u2 = new Uri(Path.GetDirectoryName(_filepath), UriKind.Absolute);
  208. Uri u3 = u1.MakeRelativeUri(u2);//u2相对于u1的uri
  209. //string ftpdir = Path.Combine(AppConfigCache.ftpPath + "/", u3.ToString());
  210. string ftpdir = Path.Combine(FtpPath, u3.ToString().Replace("../", ""));
  211. //验证文件名是否合法
  212. string filename = Path.GetFileName(_filepath);
  213. //filename : 计量作业编号_序号.jpg 计量作业编号:计量点编号+年月日时分秒
  214. CmmWorkImageEntity ci = ParseFileName(filename, ftpdir.Replace("formalImg", DateTime.Now.ToString("yyyy-MM-dd")));
  215. if (ci == null) continue;
  216. switch (Ftptype)
  217. {
  218. case "0":
  219. {
  220. if (ftpdir != lastpath)
  221. {
  222. ftp_helper.CreateDirectory(ftpdir);
  223. }
  224. ftp_helper.Put(_filepath, ftpdir, filename);
  225. };
  226. break;
  227. case "1":
  228. {
  229. vftp_helper.FtpUp(_filepath);
  230. }; break;
  231. }
  232. lastpath = ftpdir;
  233. var ccp = new CoreClientParam
  234. {
  235. ServerName = "com.steering.Mcms.CmmWorkImageServer",
  236. MethodName = "addInfo",
  237. ServerParams = new object[]
  238. {
  239. JSONFormat.Format(ci)
  240. }
  241. };
  242. ccp = OB.ExecuteNonQuery(ccp, CoreInvokeType.Internal);
  243. if (ccp.ReturnCode != -1)
  244. {
  245. WriteLog(string.Format("更新图片记录[{0}]:{1}", ci.ActualFirstNo, filename));
  246. File.Delete(_filepath);
  247. }
  248. else
  249. {
  250. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", ci.ActualFirstNo, filename));
  251. }
  252. //
  253. }
  254. catch (Exception exp)
  255. {
  256. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", _filepath, exp.Message));
  257. }
  258. }
  259. if (vftp_helper == null)
  260. {
  261. ftp_helper.Disconnect();
  262. }
  263. }
  264. /// <summary>
  265. /// 验证图片名称
  266. /// </summary>
  267. /// <param name="filename">计量点编号_作业编号_序号.jpg</param>
  268. /// <param name="ftpdir"></param>
  269. /// <returns></returns>
  270. private CmmWorkImageEntity ParseFileName(string filename, string ftpdir)
  271. {
  272. CmmWorkImageEntity ci = new CmmWorkImageEntity();
  273. filename = Path.GetFileName(filename);
  274. string[] segs = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
  275. if (segs == null || segs.Count() < 3)
  276. {
  277. WriteLog("文件名不符合要求! (3段命名):" + filename);
  278. return null;
  279. }
  280. int seq;
  281. //int icar_seq = 0;
  282. //int.TryParse(car_seq, out icar_seq);
  283. string[] seqs = segs[2].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  284. if (seqs == null || seqs.Count() == 0 || !int.TryParse(seqs[0], out seq))
  285. {
  286. WriteLog("文件名不符合要求! (序号不正确):" + filename);
  287. return null;
  288. }
  289. string fullfilename = ftpdir + "/" + filename;
  290. fullfilename = fullfilename.Replace("//", "/").Replace("//", "/");
  291. PropertyInfo pi = null;
  292. try
  293. {
  294. pi = ci.GetType().GetProperty(string.Format("ImageFile{0}", seq));
  295. pi.SetValue(ci, fullfilename.Replace("/pub", ""),null);
  296. }
  297. catch
  298. {
  299. WriteLog("文件名不符合要求! (序号超出数据库要求):" + fullfilename);
  300. return null;
  301. }
  302. //ci.image_time = DateTime.ParseExact(segs[0].Substring(segs[0].Length - 14, 14), "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
  303. ci.ActualFirstNo = segs[1];
  304. return ci;
  305. }
  306. public void Release()
  307. {
  308. try
  309. {
  310. if (ftp_helper != null)
  311. {
  312. ftp_helper.Disconnect();
  313. }
  314. if (task != null)
  315. {
  316. task.Abort();
  317. task = null;
  318. }
  319. }
  320. catch { }
  321. }
  322. private static void WriteLog(string str)
  323. {
  324. try
  325. {
  326. string m_szRunPath;
  327. m_szRunPath = System.Environment.CurrentDirectory;
  328. if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
  329. {
  330. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  331. }
  332. string strDate = System.DateTime.Now.ToString("yyyyMMdd");
  333. string strPathFile = m_szRunPath + "\\log\\" + strDate;
  334. if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
  335. {
  336. Directory.CreateDirectory(strPathFile);
  337. }
  338. System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_image_" + strDate + ".log", true);
  339. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  340. tw.WriteLine(str);
  341. tw.WriteLine("\r\n");
  342. tw.Close();
  343. }
  344. catch { }
  345. }
  346. //*/
  347. }
  348. }