ImageCurlControl.cs 17 KB

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