ImageCurlControl.cs 16 KB

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