ImageCurlControl.cs 17 KB

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