Parcourir la source

优化文件上传

yhluo il y a 5 mois
Parent
commit
97436ed8d2

+ 117 - 25
UAS_MES_BG/FunctionCode/Make/Make_ParseLog.cs

@@ -1,4 +1,5 @@
 using BarTender;
+using DevExpress.Utils.OAuth.Provider;
 using DevExpress.Xpo.Logger;
 using DevExpress.XtraEditors.Controls;
 using DevExpress.XtraExport;
@@ -11,6 +12,7 @@ using System.Data;
 using System.Drawing;
 using System.IO;
 using System.Linq;
+using System.Net;
 using System.Security;
 using System.Security.AccessControl;
 using System.Security.Principal;
@@ -52,7 +54,6 @@ namespace UAS_MES_NEW.Make
         Timer formsTimer;
         string outXmlFilePath;
 
-        BgFtpOperater ftp;
         private void Make_ParseLog_Load(object sender, EventArgs e)
         {
             dh = SystemInf.dh;
@@ -77,7 +78,6 @@ namespace UAS_MES_NEW.Make
             watcher.Deleted += OnFileChanged;
             watcher.Renamed += OnFileChanged;*/
 
-            ftp = new BgFtpOperater();
             //设置锁定工单
             LockMakeCode.GetMakeCodeCtl(ma_code);
             ma_code.SetLockCheckBox(LockMakeCode);
@@ -417,35 +417,34 @@ namespace UAS_MES_NEW.Make
                             string fileName = Path.GetFileName(file);
                             string[] lines = File.ReadAllLines(file, Encoding.GetEncoding("GB2312"));
 
-                            string modelName = lines[1].Split(',')[0];
-                            string lineNumber = lines[1].Split(',')[1];
-                            string boardStatus = lines[2].Split(',')[1];
-                            if (string.IsNullOrEmpty(boardStatus))
+                            //string modelName = lines[1].Split(',')[0];
+                            //string lineNumber = lines[1].Split(',')[1];
+                            //string boardStatus = lines[2].Split(',')[1];
+                            SN = lines[4].Split(',')[16];
+                            if (string.IsNullOrEmpty(SN))
                             {
                                 LogMessage($"文件: {file},无SN信息");
                                 continue;
                             }
-                            if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, boardStatus, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
+                            LogMessage($"文件: {file},开始上传");
+                            if (UploadFileToFtp(file))
                             {
-                                if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, boardStatus, "日志解析", "OK", User.UserCode, out oErrorMessage))
+                                dh.ExecuteSql($@"insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class,std_testresult) 
+                                                    select STEPTESTDETAIL_seq.nextval,'{SN}','{ma_code.Text}',sysdate,'思泰克SPI',
+                                                    'http://112.48.67.154:8088/ftp/mes/TestData/{DateTime.Now.ToString("yyyyMMdd")}/{Path.GetFileName(file)}.xml' from dual", "insert");
+                                
+                                string xmlContent = File.ReadAllText(file);
+                                if (ConsoleLog(xmlContent, file))
                                 {
+                                    File.Delete(file);
+                                }
+                            }
 
-                                    string ftppath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
-                                    ftp.UpLoadFile(file, boardStatus + ".xml", ftppath);
-                                    int num = int.Parse(dh.ExecuteSql("insert into STEPTESTDETAIL (std_id,std_sn,std_makecode,std_indate,std_class)select STEPTESTDETAIL_seq.nextval,ms_sncode,ms_makecode,sysdate,'http://112.48.67.154:8088/ftp" + ftppath + boardStatus + ".xml" + "' from makeserial where ms_sncode='" + boardStatus + "'", "insert").ToString());
-                                    if (num > 0)
-                                    {
-                                        LogMessage($"文件: {file},上传成功"); 
-                                        string xmlContent = File.ReadAllText(file);
-                                        if (ConsoleLog(xmlContent, file))
-                                        {
-                                            File.Delete(file);
-                                        }
-                                    }
-                                    else
-                                    {
-                                        LogMessage($"文件: {file},SN: {boardStatus}前工段未扫描");
-                                    }
+                            /*if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
+                            {
+                                if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, SN, "日志解析", "OK", User.UserCode, out oErrorMessage))
+                                {
+                                    
                                 }
                                 else
                                 {
@@ -455,7 +454,7 @@ namespace UAS_MES_NEW.Make
                             else
                             {
                                 LogMessage(">>" + oErrorMessage + "\n");
-                            }
+                            }*/
 
                             #region // 20250630 M 调整对接方式 
                             /*List<SpiData> csvData; 
@@ -731,6 +730,99 @@ namespace UAS_MES_NEW.Make
             }
         }
 
+        public bool UploadFileToFtp(string localFilePath)
+        {
+            string ftpServer = "ftp://10.8.0.208:21/mes/TestData/";
+            string username = "vsftpd";
+            string password = "vsftpd3cd79018fl";
+
+            string currentDate = DateTime.Now.ToString("yyyyMMdd");
+
+            string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{currentDate}";
+            string outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
+            if (outResult.Substring(0, 2) == "NG")
+            {
+                LogMessage(outResult);
+                return false;
+            }
+
+            string remoteFileName = Path.GetFileName(localFilePath);
+            string uri = $"{ftpFullPath}/{remoteFileName}";
+
+            try
+            {
+                var request = (FtpWebRequest)WebRequest.Create(uri);
+                request.Method = WebRequestMethods.Ftp.UploadFile;
+                request.Credentials = new NetworkCredential(username, password);
+                request.UsePassive = true;
+                request.UseBinary = true;
+                request.KeepAlive = false;
+
+                using (var fileStream = File.OpenRead(localFilePath))
+                using (var requestStream = request.GetRequestStream())
+                {
+                    byte[] buffer = new byte[4096];
+                    int bytesRead;
+                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
+                    {
+                        requestStream.Write(buffer, 0, bytesRead);
+                    }
+                }
+
+                using (var response = (FtpWebResponse)request.GetResponse())
+                {
+                    LogMessage($"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
+                    return true;
+                }
+            }
+            catch (WebException ex)
+            {
+                if (ex.Response is FtpWebResponse response)
+                {
+                    LogMessage($"FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
+                }
+                else
+                {
+                    LogMessage("Web异常: " + ex.Message);
+                }
+                return false;
+            }
+            catch (Exception ex)
+            {
+                LogMessage($"上传失败: " + ex.Message);
+                return false;
+            }
+        }
+
+        private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
+        {
+            try
+            {
+                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
+                request.Method = WebRequestMethods.Ftp.MakeDirectory;
+                request.Credentials = new NetworkCredential(username, password);
+                request.UsePassive = true;
+                request.UseBinary = true;
+                request.KeepAlive = false;
+
+                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
+                {
+                    return "OK,目录创建成功: " + response.StatusDescription;
+                }
+            }
+            catch (WebException ex)
+            {
+                if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
+                {
+                    return "OK,目录已存在: " + response.StatusDescription;
+                }
+                else
+                {
+                    return "NG,创建目录时发生错误: " + ex.Message;
+                }
+            }
+        }
+
         private void ParseLogInsert(string PathName)
         {
             try

+ 0 - 123
UAS_MES_BG/PublicMethod/BgFtpOperater.cs

@@ -1,123 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Text;
-
-namespace UAS_MES_NEW.PublicMethod
-{
-    internal class BgFtpOperater
-    {
-        private string ftpServerIP;
-        private string ftpUser;
-        private string ftpPwd;
-        public BgFtpOperater()
-        {
-            //百岗ftp
-            string[] FTPInf = "ftp://10.8.0.208:21//mes/TestData|vsftpd|Az789***".Split('|');
-            this.ftpServerIP = FTPInf[0];
-            this.ftpUser = FTPInf[1];
-            this.ftpPwd = FTPInf[2];
-            //string FTPInf = Properties.Settings.Default.Properties["FTPAddress"].DefaultValue.ToString();
-
-            //连接共享文件夹
-            //status = BaseUtil.connectState(FTPInf);
-        }
-
-        public string UpLoadFile(string filepath, string filename, string UploadFolder)
-        {
-            try
-            {
-                FtpWebRequest reqFTP;
-                if (FtpCheckDirectoryExist(UploadFolder) == "")
-                {
-                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + UploadFolder + filename));
-                    reqFTP.UseBinary = true;
-                    reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);
-                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
-                    FileInfo file = new FileInfo(filepath + "/" + filename);
-                    const int BufferSize = 2048;
-                    byte[] content = new byte[BufferSize - 1 + 1];
-                    int dataRead;
-                    using (FileStream fs = file.OpenRead())
-                    {
-                        //把上传的文件写入流
-                        using (Stream rs = reqFTP.GetRequestStream())
-                        {
-                            do
-                            {
-                                //每次读文件流的2KB
-                                dataRead = fs.Read(content, 0, BufferSize);
-                                rs.Write(content, 0, dataRead);
-                            } while (!(dataRead < BufferSize));
-                            rs.Close();
-                        }
-                        fs.Close();
-                        fs.Dispose();
-                    }
-                    file.Delete();
-                }
-
-                //Thread.Sleep(1000);
-            }
-            catch (Exception ex)
-            {
-                return ex.Message;
-            }
-            return "";
-            //File.Delete(filepath + "/" + filename);
-        }
-
-        public string FtpCheckDirectoryExist(string destFilePath)
-        {
-            string fullDir = FtpParseDirectory(destFilePath);
-            string[] dirs = fullDir.Split('/');
-            string curDir = "/";
-            for (int i = 0; i < dirs.Length; i++)
-            {
-                string dir = dirs[i];
-                //如果是以/开始的路径,第一个为空    
-                if (dir != null && dir.Length > 0)
-                {
-                    try
-                    {
-                        curDir += dir + "/";
-                        FtpMakeDir(curDir);
-                    }
-                    catch (Exception ex)
-                    {
-
-                    }
-                }
-            }
-            return "";
-        }
-
-        public string FtpParseDirectory(string destFilePath)
-        {
-            return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
-        }
-
-        public Boolean FtpMakeDir(string localFile)
-        {
-            //Console.WriteLine(ftpServerIP + localFile);
-            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + localFile);
-            try
-            {
-                req.Credentials = new NetworkCredential(ftpUser, ftpPwd);
-                req.Method = WebRequestMethods.Ftp.MakeDirectory;
-                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
-                response.Close();
-            }
-            catch (Exception ex)
-            {
-                Console.WriteLine(ex.Message);
-                req.Abort();
-                return false;
-            }
-            req.Abort();
-            return true;
-        }
-    }
-}

+ 0 - 1
UAS_MES_BG/UAS_MES_BG.csproj

@@ -1188,7 +1188,6 @@
     <Compile Include="PublicMethod\AutoSizeControl.cs" />
     <Compile Include="PublicMethod\AutoSizeFormClass.cs" />
     <Compile Include="PublicMethod\BaseUtil.cs" />
-    <Compile Include="PublicMethod\BgFtpOperater.cs" />
     <Compile Include="PublicMethod\DrawHelper.cs" />
     <Compile Include="PublicMethod\Encryption.cs" />
     <Compile Include="PublicMethod\ExceptionHandler.cs" />