Forráskód Böngészése

参估检测工具使用API接口

wyq 1 éve
szülő
commit
8184626a7f

+ 45 - 59
XdCxRhDW.App/CorTools/DetectToolForm.cs

@@ -3,18 +3,26 @@ using DevExpress.Internal.WinApi.Windows.UI.Notifications;
 using DevExpress.Mvvm.Native;
 using DevExpress.XtraEditors;
 using DevExpress.XtraLayout.Utils;
+using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
+using System.Data.Entity;
 using System.Drawing;
 using System.IO;
 using System.IO.Compression;
 using System.Linq;
+using System.Net;
 using System.Net.Http;
 using System.Text;
 using System.Threading.Tasks;
+using System.Web.Http.Results;
+using System.Web.UI.WebControls;
 using System.Windows.Forms;
+using XdCxRhDW.App.EFContext;
+using XdCxRhDW.App.WebAPI;
+using static XdCxRhDW.App.WebAPI.BaseController;
 
 namespace XdCxRhDW.App.CorTools
 {
@@ -22,6 +30,7 @@ namespace XdCxRhDW.App.CorTools
     {
         static readonly string inifile = Path.Combine(Application.StartupPath, "par.ini");
         volatile bool beRunning = false;
+        private  string uploadUrL;
         BindingList<CafResult> gridSource = new BindingList<CafResult>();
 
         public DetectToolForm()
@@ -86,7 +95,7 @@ namespace XdCxRhDW.App.CorTools
             File.WriteAllLines(inifile, lines);
         }
 
-        private void MainForm_Load(object sender, EventArgs e)
+        private async void MainForm_Load(object sender, EventArgs e)
         {
             this.gridControl1.DataSource = gridSource;
             ReadIni();
@@ -239,7 +248,6 @@ namespace XdCxRhDW.App.CorTools
                 chkDama.Checked = false;
             }
         }
-
         private async void btnCalc_Click(object sender, EventArgs e)
         {
             if (btnCalc.Text == "停止")
@@ -257,56 +265,20 @@ namespace XdCxRhDW.App.CorTools
             {
                 return;
             }
-
-
-            // 压缩文件
-            string compressedFilePath = CompressFile(btnFile1.Text);
-
-            // 创建 HttpClient 对象
-            using (HttpClient client = new HttpClient())
+            List<XcorrStruct> xcorrs = new List<XcorrStruct>();
+            XcorrStruct xItem = new XcorrStruct();
+            try
             {
-                // 构建上传请求的 Uri
-                string uploadUri = "http://localhost:8091/api/DetectCg/UploadFile"; 
-
-                // 创建 MultipartFormDataContent 用于封装文件内容
-                MultipartFormDataContent content = new MultipartFormDataContent();
-
-                // 添加压缩后的文件内容到 MultipartFormDataContent
-                byte[] fileBytes = File.ReadAllBytes(compressedFilePath);
-                ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
-                content.Add(fileContent, "file", Path.GetFileName(compressedFilePath));
-
-                try
+                using (RHDWContext db = new RHDWContext())
                 {
-                    // 发送上传请求
-                    HttpResponseMessage response = await client.PostAsync(uploadUri, content);
-
-                    // 检查响应状态码
-                    if (response.IsSuccessStatusCode)
-                    {
-                        MessageBox.Show("文件上传成功!");
-                    }
-                    else
+                    var res = await db.SysSetings.FirstOrDefaultAsync();
+                    if (res != null)
                     {
-                        MessageBox.Show("文件上传失败!");
+                        uploadUrL = $"http://{res.ServerIp}:{res.HttpPort}/api/DetectCg";
                     }
                 }
-                catch (Exception ex)
-                {
-                    MessageBox.Show("文件上传失败:" + ex.Message);
-                }
-            }
-
-            // 删除压缩后的临时文件
-            File.Delete(compressedFilePath);
-
-            List<XcorrStruct> xcorrs = new List<XcorrStruct>();
-            XcorrStruct xItem = new XcorrStruct();
-            xItem.file1 = btnFile1.Text;
-            xItem.file2 = btnFile2.Text;
-            try
-            {
-
+                xItem.file1 = UpLoadFile(btnFile1.Text);
+                xItem.file2 = UpLoadFile(btnFile2.Text);
                 xItem.smpCount = int.Parse(teCount.Text);
                 xItem.samplingRate = Convert.ToInt32(double.Parse(tefs.Text) * 1e6);
                 xItem.dtCenter = int.Parse(teCenter.Text);
@@ -343,7 +315,12 @@ namespace XdCxRhDW.App.CorTools
             gridSource.Clear();
             foreach (var xcitem in xcorrs)
             {
-                var result = await ExecuteCorAsync(xcitem);
+                // 构建上传请求的 Uri
+                string uploadUri = $"{uploadUrL}/EstimationCalc";
+
+                var content = new StringContent(JsonConvert.SerializeObject(xcitem), System.Text.Encoding.UTF8, "application/json");
+                var result = PostRequest<CafResult>(uploadUri, content);
+               // var result = await ExecuteCorAsync(xcitem);
                 if (result != null)
                 {
                     //var smitemindex = gridSource.FindIndex(m => m.smpstart == xcitem.smpStart && m.smplen == xcitem.smpCount);
@@ -370,22 +347,31 @@ namespace XdCxRhDW.App.CorTools
             beRunning = false;
 
         }
-        private string CompressFile(string filePath)
+        private string UpLoadFile(string filePath)
         {
-            string compressedFilePath = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + ".zip");
+            string file = string.Empty;
+            // 构建上传请求的 Uri
+            string uploadUri =$"{uploadUrL}/UploadFile";
+
+            // 添加文件内容到 MultipartFormDataContent
+            byte[] fileBytes = File.ReadAllBytes(filePath);
 
-            using (FileStream originalFileStream = File.OpenRead(filePath))
+            // 创建 MultipartFormDataContent 用于封装文件内容
+            MultipartFormDataContent content = new MultipartFormDataContent();
+            ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
+            content.Add(fileContent, "file", Path.GetFileName(filePath));
+            try
             {
-                using (FileStream compressedFileStream = File.Create(compressedFilePath))
-                {
-                    using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
-                    {
-                        originalFileStream.CopyTo(compressionStream);
-                    }
-                }
+                // 发送上传请求
+                 file = PostRequest<string>(uploadUri, content);
+            }
+            catch (Exception ex)
+            {
+                throw new Exception($"上传文件{filePath}到{uploadUri}失败!");
             }
 
-            return compressedFilePath;
+
+            return file;
         }
         private async Task<CafResult> ExecuteCorAsync(XcorrStruct xItem)
         {

+ 42 - 2
XdCxRhDW.App/WebAPI/Controllers/BaseController.cs

@@ -1,4 +1,5 @@
-using System;
+using Newtonsoft.Json;
+using System;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Linq;
@@ -41,6 +42,45 @@ namespace XdCxRhDW.App.WebAPI
                 throw ex;
             }
         }
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <typeparam name="T"></typeparam>
+        /// <param name="url"></param>
+        /// <param name="data"></param>
+        /// <returns></returns>
+        public static T PostRequest<T>(string url, HttpContent data)
+        {
+            try
+            {
+                var handler = new HttpClientHandler() { UseCookies = false };
+                HttpClient client = new HttpClient(handler);
+                client.Timeout = TimeSpan.FromSeconds(10);
+                var message = new HttpRequestMessage(HttpMethod.Post, url);
+                message.Content = data;
+                var response = client.SendAsync(message).Result;
+                response.EnsureSuccessStatusCode();
+                var result = response.Content.ReadAsStringAsync().Result;
+                var AjaxResult = JsonConvert.DeserializeObject<AjaxResult>(result);
+                if (AjaxResult.code == 200)
+                {
+                    if (AjaxResult.data.GetType().ToString().Contains("System.String"))
+                    {
+                        return (T)AjaxResult.data;
+                    }
+                    var pres = JsonConvert.DeserializeObject<T>(AjaxResult.data.ToString());
+                    return pres;
+                }
+                else
+                {
+                    return default(T);
+                }
+            }
+            catch (Exception ex)
+            {
+                throw ex;
+            }
+        }
 
         /// <summary>
         /// Http返回结果
@@ -102,7 +142,7 @@ namespace XdCxRhDW.App.WebAPI
         /// <param name="msg">返回的消息</param>
         /// <param name="data">返回的数据</param>
         /// <returns></returns>
-        protected AjaxResult Success(object data,string msg= "请求成功!")
+        protected AjaxResult Success(object data, string msg = "请求成功!")
         {
             AjaxResult res = new AjaxResult
             {

+ 1 - 2
XdCxRhDW.App/WebAPI/Controllers/DetectCgController.cs

@@ -130,9 +130,8 @@ namespace XdCxRhDW.App.WebAPI
         {
             if (!Request.Content.IsMimeMultipartContent("form-data"))
             {
-                return Error<string>("不支持当前媒介类型");
+                return Error<string>("请求数据不是multipart/form-data类型");
             }
-
             var provider = new MultipartMemoryStreamProvider();
             await Request.Content.ReadAsMultipartAsync(provider);