| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395 |
- using Core.Mes.Client.Comm.Format;
- using Core.StlMes.Client.LgResMgt.Mcms.entity;
- using CoreFS.CA06;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Serialization;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading;
- namespace Core.StlMes.Client.LgResMgt.Mcms
- {
- /// <summary>
- /// 在进入系统后,需开启这个线程用于每10秒上传一次图片到ftp服务器
- /// 在退出系统后,需关闭这个线程
- /// </summary>
- public class ImageControl
- {
- SFTPHelper ftp_helper;
- VSFTPHelper vftp_helper;
- Thread task;
- string FtpIp { get; set; }
- int FtpPort { get; set; }
- string Username { get; set; }
- string FtpPwd { get; set; }
- string Ftptype { get; set; }
- string FtpPath { get; set; }
- public OpeBase OB { get; set; }
- public ImageControl(string ftpIp ,string ftpPort,string username,string ftpPwd ,string ftptype,string path , OpeBase ob)
- {
- FtpPort = Convert.ToInt32(ftpPort);
- FtpIp = ftpIp;
- Username = username;
- FtpPwd = ftpPwd;
- Ftptype = ftptype;
- FtpPath = path;
- OB = ob;
- switch (ftptype)//区别在哪。先确认一下
- {
- case "0":
- ftp_helper = new SFTPHelper(ftpIp, FtpPort, username, ftpPwd);
- break;
- case "1":
- vftp_helper = new VSFTPHelper( ftpIp, username, ftpPwd, path);
- break;
- }
- }
-
- public void Start()
- {
- if (task == null)
- {
- task = new Thread(new ThreadStart(Doworks));
- task.Start();
- }
- }
- public void Stop()
- {
- if (task != null)
- {
- task.Abort();
- task = null;
- }
- }
- private void Doworks()
- {
- do
- {
- int waitSecs = 10000;
- int i = 0;
- try
- {
- string sPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\imgShort\\";
- i = 1;
- string picPath = Path.Combine(sPath, "tempImg");
- i = 2;
- ArrayList UnZipedFiles = GetFiles(picPath, ".jpg");//tmp!
- i = 3;
- //ZipFiles(UnZipedFiles); //2021年3月2日不再进行图片压缩,直接存到正式文件夹formalImg中
- i = 4;
- //获取正式目录文件进行上传
- ArrayList files = GetFiles(sPath + "formalImg", ".jpg");
- i = 5;
- UploadFiles(files);
- i = 6;
- //删除正式目录文件
- RemoveRedundantDir(Path.Combine(sPath, "formalImg"), 0);
- i = 7;
- }
- catch (Exception exp)
- {
- WriteLog("ImageControl.Doworks在" + i + "位置异常,异常信息:" + exp.Message);
- }
- finally
- {
- Thread.Sleep(waitSecs);
- }
- } while (true);
- }
- private void RemoveRedundantDir(string _path, int deep)
- {
- DirectoryInfo theFolder = new DirectoryInfo(_path);
- DirectoryInfo[] dirInfos = theFolder.GetDirectories();
- if (dirInfos != null && dirInfos.Count() > 0)
- {
- foreach (DirectoryInfo di in dirInfos)
- {
- RemoveRedundantDir(di.FullName, deep + 1);
- }
- }
- try
- {
- if (deep == 0) return;
- FileInfo[] fileinfos = theFolder.GetFiles();
- if (fileinfos == null || fileinfos.Count() == 0)
- {
- DateTime dt;
- if (DateTime.TryParseExact(theFolder.Name, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.AllowWhiteSpaces, out dt))
- {
- if (TimeSpan.FromTicks(DateTime.Today.Ticks).Subtract(TimeSpan.FromTicks(dt.Date.Ticks)).TotalDays > 1)
- {
- Directory.Delete(_path);
- }
- }
- }
- }
- catch { }
- }
- private void ZipFiles(ArrayList UnzipedFiles)
- {
- ImageZip iz = new ImageZip();
- if (UnzipedFiles == null || UnzipedFiles.Count == 0) return;
- foreach (string fn in UnzipedFiles)
- {
- if (string.IsNullOrEmpty(fn)) continue;
- if (!File.Exists(fn)) continue;
- //临时目录图片压缩后存储与正式目录
- string jpgFile = fn.Replace("tempImg", "formalImg");
- Image img = ImageZip.BytesToBitmap(ImageZip.ZipImageByte(fn));
- if (img != null)
- {
- //iz.ResourceImage = img;
- //压缩图片并保存
- //iz.GetReducedImage(AppConfigCache.imgWidth, AppConfigCache.imgHeight).Save(jpgFile);
- img.Save(jpgFile);
- File.Delete(fn);//删除临时目录数据
- }
- else
- {
- iz.ResourceImage = img;
- //压缩图片并保存
- iz.GetReducedImage(400, 400).Save(jpgFile);
- //File.Move(fn, jpgFile);
- }
- }
- }
- private ArrayList GetFiles(string _dirPath, string extensionName)
- {
- ArrayList files = new ArrayList();
- if (!Directory.Exists(_dirPath)) return null;
- DirectoryInfo theFolder = new DirectoryInfo(_dirPath);
- FileInfo[] fileinfos = theFolder.GetFiles("*" + extensionName);
- if (fileinfos != null && fileinfos.Count() > 0)
- {
- foreach (FileInfo fi in fileinfos)
- {
- files.Add(fi.FullName);
- }
- }
- DirectoryInfo[] dirInfos = theFolder.GetDirectories();
- if (dirInfos != null && dirInfos.Count() > 0)
- {
- foreach (DirectoryInfo di in dirInfos)
- {
- files.AddRange(GetFiles(di.FullName, extensionName));
- }
- }
- return files;
- }
- // 后台刷FTP线程调用
- private void UploadFiles(ArrayList files)
- {
- if ("0".Equals(Ftptype))
- {
- if (files == null || files.Count == 0 || ftp_helper == null) return;
- }
- else
- {
- if (files == null || files.Count == 0 || vftp_helper == null) return;
- }
- if (Ftptype == "0")
- {
- if (!ftp_helper.Connect()) return;
- }
- string localpath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"imgShort\formalImg\"));
- string lastpath = FtpPath;
- foreach (string _filepath in files)
- {
- try
- {
- //计算ftp相对路径
- Uri u1 = new Uri(localpath, UriKind.Absolute);
- Uri u2 = new Uri(Path.GetDirectoryName(_filepath), UriKind.Absolute);
- Uri u3 = u1.MakeRelativeUri(u2);//u2相对于u1的uri
- //string ftpdir = Path.Combine(AppConfigCache.ftpPath + "/", u3.ToString());
- string ftpdir = Path.Combine(FtpPath, u3.ToString().Replace("../", ""));
- //验证文件名是否合法
- string filename = Path.GetFileName(_filepath);
- //filename : 计量作业编号_序号.jpg 计量作业编号:计量点编号+年月日时分秒
- CmmWorkImageEntity ci = ParseFileName(filename, ftpdir.Replace("formalImg", DateTime.Now.ToString("yyyy-MM-dd")));
- if (ci == null) continue;
- switch (Ftptype)
- {
- case "0":
- {
- if (ftpdir != lastpath)
- {
- ftp_helper.CreateDirectory(ftpdir);
- }
- ftp_helper.Put(_filepath, ftpdir, filename);
- };
- break;
- case "1":
- {
- vftp_helper.FtpUp(_filepath);
- }; break;
- }
- lastpath = ftpdir;
- var ccp = new CoreClientParam
- {
- ServerName = "com.steering.Mcms.CmmWorkImageServer",
- MethodName = "addInfo",
- ServerParams = new object[]
- {
- JSONFormat.Format(ci)
-
- }
- };
- ccp = OB.ExecuteNonQuery(ccp, CoreInvokeType.Internal);
- if (ccp.ReturnCode != -1)
- {
- WriteLog(string.Format("更新图片记录[{0}]:{1}", ci.ActualFirstNo, filename));
- File.Delete(_filepath);
- }
- else
- {
- WriteLog(string.Format("上传图片失败! [{0}]\n{1}", ci.ActualFirstNo, filename));
- }
- //
- }
- catch (Exception exp)
- {
- WriteLog(string.Format("上传图片失败! [{0}]\n{1}", _filepath, exp.Message));
- }
- }
- if (vftp_helper == null)
- {
- ftp_helper.Disconnect();
- }
- }
- /// <summary>
- /// 验证图片名称
- /// </summary>
- /// <param name="filename">计量点编号_作业编号_序号.jpg</param>
- /// <param name="ftpdir"></param>
- /// <returns></returns>
- private CmmWorkImageEntity ParseFileName(string filename, string ftpdir)
- {
- CmmWorkImageEntity ci = new CmmWorkImageEntity();
- filename = Path.GetFileName(filename);
- string[] segs = filename.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
- if (segs == null || segs.Count() < 3)
- {
- WriteLog("文件名不符合要求! (3段命名):" + filename);
- return null;
- }
- int seq;
- //int icar_seq = 0;
- //int.TryParse(car_seq, out icar_seq);
- string[] seqs = segs[2].Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
- if (seqs == null || seqs.Count() == 0 || !int.TryParse(seqs[0], out seq))
- {
- WriteLog("文件名不符合要求! (序号不正确):" + filename);
- return null;
- }
- string fullfilename = ftpdir + "/" + filename;
- fullfilename = fullfilename.Replace("//", "/").Replace("//", "/");
- PropertyInfo pi = null;
- try
- {
- pi = ci.GetType().GetProperty(string.Format("ImageFile{0}", seq));
- pi.SetValue(ci, fullfilename.Replace("/pub", ""),null);
- }
- catch
- {
- WriteLog("文件名不符合要求! (序号超出数据库要求):" + fullfilename);
- return null;
- }
- //ci.image_time = DateTime.ParseExact(segs[0].Substring(segs[0].Length - 14, 14), "yyyyMMddHHmmss", CultureInfo.CurrentCulture);
- ci.ActualFirstNo = segs[1];
- return ci;
- }
- public void Release()
- {
- try
- {
- if (ftp_helper != null)
- {
- ftp_helper.Disconnect();
- }
- if (task != null)
- {
- task.Abort();
- task = null;
- }
- }
- catch { }
- }
- private static void WriteLog(string str)
- {
- try
- {
- string m_szRunPath;
- m_szRunPath = System.Environment.CurrentDirectory;
- if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
- {
- System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
- }
- string strDate = System.DateTime.Now.ToString("yyyyMMdd");
- string strPathFile = m_szRunPath + "\\log\\" + strDate;
- if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
- {
- Directory.CreateDirectory(strPathFile);
- }
- System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\FTP_image_" + strDate + ".log", true);
- tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
- tw.WriteLine(str);
- tw.WriteLine("\r\n");
- tw.Close();
- }
- catch { }
- }
- //*/
- }
- }
|