ImageCurlControl.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. private 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. string ftpdir = Path.Combine(AppConfigCache.ftpPath, DateTime.Now.ToString("yyyy-MM-dd"));
  119. //验证文件名是否合法
  120. string filename = Path.GetFileName(_filepath);
  121. //filename : 计量作业编号_序号.jpg 计量作业编号:计量点编号+年月日时分秒
  122. MeterWorkImage ci = ParseFileName(filename, ftpdir.Replace("upload", "download"));
  123. if (ci == null) continue;
  124. // 上传文件
  125. UploadRequest(ftpdir, localpath + filename);
  126. //存储计量数据的时候,实际上是先将计量数据及图片路径
  127. MeterWorkImageService service = new MeterWorkImageService();
  128. RESTfulResult<string> rm = service.doSaveWf(ci); //db.doOption<string>("MeterWorkImageService", "doSaveWf", new object[] { ci }, 1);
  129. if (rm.Succeed)
  130. {
  131. WriteLog(string.Format("更新图片记录[{0}]:{1}", ci.actualFirstNo, filename));
  132. File.Delete(_filepath);
  133. }
  134. else
  135. {
  136. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", ci.actualFirstNo, filename));
  137. }
  138. //
  139. }
  140. catch (Exception exp)
  141. {
  142. WriteLog(string.Format("上传图片失败! [{0}]\n{1}", _filepath, exp.Message));
  143. }
  144. }
  145. }
  146. private void RemoveRedundantDir(string _path, int deep)
  147. {
  148. DirectoryInfo theFolder = new DirectoryInfo(_path);
  149. DirectoryInfo[] dirInfos = theFolder.GetDirectories();
  150. if (dirInfos != null && dirInfos.Count() > 0)
  151. {
  152. foreach (DirectoryInfo di in dirInfos)
  153. {
  154. RemoveRedundantDir(di.FullName, deep + 1);
  155. }
  156. }
  157. try
  158. {
  159. if (deep == 0) return;
  160. FileInfo[] fileinfos = theFolder.GetFiles();
  161. if (fileinfos == null || fileinfos.Count() == 0)
  162. {
  163. DateTime dt;
  164. if (DateTime.TryParseExact(theFolder.Name, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
  165. {
  166. if (TimeSpan.FromTicks(DateTime.Today.Ticks).Subtract(TimeSpan.FromTicks(dt.Date.Ticks)).TotalDays > 1)
  167. {
  168. Directory.Delete(_path);
  169. }
  170. }
  171. }
  172. }
  173. catch { }
  174. }
  175. /// <summary>
  176. /// 验证图片名称
  177. /// </summary>
  178. /// <param name="filename">计量点编号_作业编号_序号.jpg</param>
  179. /// <param name="ftpdir"></param>
  180. /// <returns></returns>
  181. private MeterWorkImage ParseFileName(string filename, string ftpdir)
  182. {
  183. MeterWorkImage ci = new MeterWorkImage();
  184. filename = Path.GetFileName(filename);
  185. string[] segs = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
  186. if (segs == null || segs.Count() < 3)
  187. {
  188. WriteLog("文件名不符合要求! (3段命名):" + filename);
  189. return null;
  190. }
  191. int seq;
  192. //int icar_seq = 0;
  193. //int.TryParse(car_seq, out icar_seq);
  194. string[] seqs = segs[2].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
  195. if (seqs == null || seqs.Count() == 0 || !int.TryParse(seqs[0], out seq))
  196. {
  197. WriteLog("文件名不符合要求! (序号不正确):" + filename);
  198. return null;
  199. }
  200. string fullfilename = ftpdir + "/" + filename;
  201. if (fullfilename.Substring(0, 8) == "https://")
  202. {
  203. fullfilename = fullfilename.Substring(0, 8) + fullfilename.Substring(8).Replace("//", "/").Replace("//", "/");
  204. }
  205. else if (fullfilename.Substring(0, 7) == "http://")
  206. {
  207. fullfilename = fullfilename.Substring(0, 7) + fullfilename.Substring(7).Replace("//", "/").Replace("//", "/");
  208. }
  209. else
  210. {
  211. fullfilename = fullfilename.Replace("//", "/").Replace("//", "/");
  212. }
  213. PropertyInfo pi = null;
  214. try
  215. {
  216. pi = ci.GetType().GetProperty(string.Format("imageFile{0}", seq));
  217. pi.SetValue(ci, fullfilename.Replace("/pub", ""));
  218. }
  219. catch
  220. {
  221. WriteLog("文件名不符合要求! (序号超出数据库要求):" + fullfilename);
  222. return null;
  223. }
  224. //ci.image_time = DateTime.ParseExact(segs[0].Substring(segs[0].Length - 14, 14), "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
  225. ci.actualFirstNo = segs[1];
  226. return ci;
  227. }
  228. private static void WriteLog(string str)
  229. {
  230. try
  231. {
  232. string m_szRunPath;
  233. m_szRunPath = System.Environment.CurrentDirectory;
  234. if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
  235. {
  236. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  237. }
  238. string strDate = System.DateTime.Now.ToString("yyyyMMdd");
  239. string strPathFile = m_szRunPath + "\\log\\" + strDate;
  240. if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
  241. {
  242. Directory.CreateDirectory(strPathFile);
  243. }
  244. System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_image_" + strDate + ".log", true);
  245. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  246. tw.WriteLine(str);
  247. tw.WriteLine("\r\n");
  248. tw.Close();
  249. }
  250. catch { }
  251. }
  252. private void UploadRequest(string url, string filePath)
  253. {
  254. // 时间戳,用做boundary
  255. string timeStamp = DateTime.Now.Ticks.ToString("x");
  256. //根据uri创建HttpWebRequest对象
  257. HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
  258. //如果是发送HTTPS请求
  259. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  260. {
  261. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  262. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
  263. | SecurityProtocolType.Tls
  264. | (SecurityProtocolType)0x300 //Tls11
  265. | (SecurityProtocolType)0xC00; //Tls12
  266. oWebrequest = WebRequest.Create(url) as HttpWebRequest;
  267. oWebrequest.ProtocolVersion = HttpVersion.Version11;
  268. }
  269. else
  270. {
  271. oWebrequest = WebRequest.Create(url) as HttpWebRequest;
  272. }
  273. //HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  274. oWebrequest.Method = "POST";
  275. oWebrequest.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  276. oWebrequest.Timeout = 300000; //设置获得响应的超时时间(300秒)
  277. oWebrequest.ContentType = "multipart/form-data; boundary=" + timeStamp;
  278. //文件
  279. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  280. BinaryReader binaryReader = new BinaryReader(fileStream);
  281. //头信息
  282. string boundary = "--" + timeStamp;
  283. string dataFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
  284. string header = string.Format(dataFormat, "file", Path.GetFileName(filePath));
  285. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header);
  286. //结束边界
  287. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n");
  288. long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
  289. oWebrequest.ContentLength = length;//请求内容长度
  290. try
  291. {
  292. //每次上传4k
  293. int bufferLength = 4096;
  294. byte[] buffer = new byte[bufferLength];
  295. //已上传的字节数
  296. long offset = 0;
  297. int size = binaryReader.Read(buffer, 0, bufferLength);
  298. Stream postStream = oWebrequest.GetRequestStream();
  299. //发送请求头部消息
  300. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  301. while (size > 0)
  302. {
  303. postStream.Write(buffer, 0, size);
  304. offset += size;
  305. size = binaryReader.Read(buffer, 0, bufferLength);
  306. }
  307. //添加尾部边界
  308. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  309. postStream.Close();
  310. //获取服务器端的响应
  311. using (HttpWebResponse response = (HttpWebResponse)oWebrequest.GetResponse())
  312. {
  313. Stream receiveStream = response.GetResponseStream();
  314. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  315. string returnValue = readStream.ReadToEnd();
  316. response.Close();
  317. readStream.Close();
  318. }
  319. }
  320. catch (Exception ex)
  321. {
  322. //Debug.WriteLine("文件传输异常: " + ex.Message);
  323. }
  324. finally
  325. {
  326. fileStream.Close();
  327. binaryReader.Close();
  328. }
  329. }
  330. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  331. {
  332. return true; //总是接受
  333. }
  334. }
  335. }