ImageCurlControl.cs 14 KB

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