From d1a5186b04281d9de683ec2efd340250b8f49fb2 Mon Sep 17 00:00:00 2001 From: lgd Date: Thu, 17 Apr 2025 14:48:05 +0800 Subject: [PATCH] =?UTF-8?q?shape=E4=B8=8A=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Infrastructure/Utils/GeoUtil.cs | 55 +- .../BaseApp/DbTable/Request/DbTableReq.cs | 2 - .../ServiceApp/LayerManagerApp/LayerApp.cs | 1011 +++++++++++++++-- .../DataMaintenance/LayerController.cs | 121 +- OpenAuth.WebApi/appsettings.json | 2 +- 5 files changed, 1046 insertions(+), 145 deletions(-) diff --git a/Infrastructure/Utils/GeoUtil.cs b/Infrastructure/Utils/GeoUtil.cs index fd09bff..7014d00 100644 --- a/Infrastructure/Utils/GeoUtil.cs +++ b/Infrastructure/Utils/GeoUtil.cs @@ -3,6 +3,7 @@ using System.Net; using System.Net.Http.Headers; using System.Text; using System.Xml.Linq; +using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OSGeo.GDAL; @@ -1149,4 +1150,56 @@ public class GeoUtil obj.srs = epsgCode; return obj; } -} \ No newline at end of file + /// + /// 更新图层样式 + /// + private static async Task UpdateLayerStyleAsync(string layerName, string style) + { + // 构建请求 URL + string url = $"{GeoserverUrl}/rest/layers/{Workspace}:{layerName}"; + + // 构建请求体 + var requestBody = new + { + layer = new + { + defaultStyle = new + { + name = style, + workspace = Workspace + } + } + }; + + // 将请求体序列化为 JSON + string jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(requestBody); + + // 创建 HttpClient + using (HttpClient client = new HttpClient()) + { + // 设置基本认证 + var authHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{Username}:{Password}")); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeader); + + // 设置请求头 + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // 发送 PUT 请求 + HttpContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); + HttpResponseMessage response = await client.PutAsync(url, content); + + // 检查响应状态 + if (response.IsSuccessStatusCode) + { + return true; // 更新成功 + } + else + { + // 输出错误信息 + string errorResponse = await response.Content.ReadAsStringAsync(); + Console.WriteLine($"错误响应: {errorResponse}"); + return false; // 更新失败 + } + } + } + } \ No newline at end of file diff --git a/OpenAuth.App/BaseApp/DbTable/Request/DbTableReq.cs b/OpenAuth.App/BaseApp/DbTable/Request/DbTableReq.cs index ece0357..e637945 100644 --- a/OpenAuth.App/BaseApp/DbTable/Request/DbTableReq.cs +++ b/OpenAuth.App/BaseApp/DbTable/Request/DbTableReq.cs @@ -10,8 +10,6 @@ namespace OpenAuth.App.Request { public string TableName { get; set; } - public int Id { get; set; } - public List> list { get; set; } } } diff --git a/OpenAuth.App/ServiceApp/LayerManagerApp/LayerApp.cs b/OpenAuth.App/ServiceApp/LayerManagerApp/LayerApp.cs index 63ff16c..98ca195 100644 --- a/OpenAuth.App/ServiceApp/LayerManagerApp/LayerApp.cs +++ b/OpenAuth.App/ServiceApp/LayerManagerApp/LayerApp.cs @@ -22,7 +22,16 @@ using DocumentFormat.OpenXml.Bibliography; using OpenAuth.App.Request; using System.IO; using DocumentFormat.OpenXml.Math; - +using Microsoft.AspNetCore.Http; +using NPOI.SS.Formula.Functions; +using OpenAuth.App.FormScheme.FormHelpers; +using System.Text; +using System.IO.Compression; +using NetTopologySuite.IO; +using NetTopologySuite.Features; +using OSGeo.OGR; +using Shapefile = NetTopologySuite.IO.Esri.Shapefile; +using Org.BouncyCastle.Ocsp; namespace OpenAuth.App.ServiceApp.LayerManagerApp; public class LayerApp : SqlSugarBaseApp @@ -305,110 +314,229 @@ public class LayerApp : SqlSugarBaseApp Result = result }; } - public Response TempeleteByTableName(string tablename) + public Response TempeleteByTableName(string tablename,int type, string shpFilePath, string shpFilePathzip) { Response response = new Response(); string sql = $"select column_name as name from INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'public' AND table_name ='" + tablename + "'"; var cloumnlist = _client.Ado.SqlQuery(sql); - try + if (type == 0) { - HSSFWorkbook workbook = new HSSFWorkbook(); + try + { + HSSFWorkbook workbook = new HSSFWorkbook(); - IFont font = workbook.CreateFont(); //创建一个字体样式对象 - font.FontName = "Microsoft YaHei"; //和excel里面的字体对应 - font.Boldweight = (short)FontBoldWeight.Bold; //字体加粗 - font.FontHeightInPoints = 12; //字体大小 - ICellStyle style1 = workbook.CreateCellStyle(); //创建样式对象 - style1.BorderBottom = BorderStyle.Thin; - style1.BorderLeft = BorderStyle.Thin; - style1.BorderRight = BorderStyle.Thin; - style1.BorderTop = BorderStyle.Thin; - style1.Alignment = HorizontalAlignment.Center; - style1.VerticalAlignment = VerticalAlignment.Center; - style1.SetFont(font); //将字体样式赋给样式对象 + IFont font = workbook.CreateFont(); //创建一个字体样式对象 + font.FontName = "Microsoft YaHei"; //和excel里面的字体对应 + font.Boldweight = (short)FontBoldWeight.Bold; //字体加粗 + font.FontHeightInPoints = 12; //字体大小 + ICellStyle style1 = workbook.CreateCellStyle(); //创建样式对象 + style1.BorderBottom = BorderStyle.Thin; + style1.BorderLeft = BorderStyle.Thin; + style1.BorderRight = BorderStyle.Thin; + style1.BorderTop = BorderStyle.Thin; + style1.Alignment = HorizontalAlignment.Center; + style1.VerticalAlignment = VerticalAlignment.Center; + style1.SetFont(font); //将字体样式赋给样式对象 - // 创建一个数值格式的CellStyle - ICellStyle numericStyle = workbook.CreateCellStyle(); + // 创建一个数值格式的CellStyle + ICellStyle numericStyle = workbook.CreateCellStyle(); - // 创建一个数据格式对象 - IDataFormat dataFormat = workbook.CreateDataFormat(); - var font11 = workbook.CreateFont(); - font11.FontName = "Microsoft YaHei"; - font11.FontHeightInPoints = 12; - // 设置单元格格式为数值型 - numericStyle.DataFormat = dataFormat.GetFormat("0.00"); - numericStyle.BorderBottom = BorderStyle.Thin; - numericStyle.BorderLeft = BorderStyle.Thin; - numericStyle.BorderRight = BorderStyle.Thin; - numericStyle.BorderTop = BorderStyle.Thin; - numericStyle.Alignment = HorizontalAlignment.Center; - numericStyle.VerticalAlignment = VerticalAlignment.Center; - numericStyle.SetFont(font11); - ISheet sheet = workbook.CreateSheet("Sheet0"); - IRow rowHeader = sheet.CreateRow(0); - rowHeader.Height = 20 * 30; + // 创建一个数据格式对象 + IDataFormat dataFormat = workbook.CreateDataFormat(); + var font11 = workbook.CreateFont(); + font11.FontName = "Microsoft YaHei"; + font11.FontHeightInPoints = 12; + // 设置单元格格式为数值型 + numericStyle.DataFormat = dataFormat.GetFormat("0.00"); + numericStyle.BorderBottom = BorderStyle.Thin; + numericStyle.BorderLeft = BorderStyle.Thin; + numericStyle.BorderRight = BorderStyle.Thin; + numericStyle.BorderTop = BorderStyle.Thin; + numericStyle.Alignment = HorizontalAlignment.Center; + numericStyle.VerticalAlignment = VerticalAlignment.Center; + numericStyle.SetFont(font11); + ISheet sheet = workbook.CreateSheet("Sheet0"); + IRow rowHeader = sheet.CreateRow(0); + rowHeader.Height = 20 * 30; + for (int i = 0; i < cloumnlist.Count; i++) + { + var header = cloumnlist[i]; + rowHeader.CreateCell(i); + rowHeader.Cells[i].CellStyle = style1; + rowHeader.Cells[i].SetCellValue(header); + } + response.Result = new MemoryStream(); + workbook.Write(response.Result); + workbook = null; + response.Result.Close(); + response.Result.Dispose(); + response.Code = 200; + response.Message = "获取成功"; + + } + catch (Exception ex) + { + response.Code = 500; + response.Message = ex.Message; + } + } + + if (type == 1) + { + List features = new List(); + var attributes = new AttributesTable(); + string wkt = "POINT(117.968055555555 35.4761111111111)"; + var geometry = ParseGeometry(wkt); for (int i = 0; i < cloumnlist.Count; i++) { + var header = cloumnlist[i]; - rowHeader.CreateCell(i); - rowHeader.Cells[i].CellStyle = style1; - rowHeader.Cells[i].SetCellValue(header); + if (header.Contains("geom")) + { + continue; + } + attributes.Add(header, 11); } - response.Result = new MemoryStream(); - workbook.Write(response.Result); - workbook = null; - response.Result.Close(); - response.Result.Dispose(); - response.Code = 200; - response.Message = "获取成功"; - } - catch (Exception ex) - { - response.Code = 500; - response.Message = ex.Message; + IFeature feature = new NetTopologySuite.Features.Feature(geometry, attributes); + features.Add(feature); + // 导出 SHP 文件及其关联文件 + ExportToShapefileFour(shpFilePath, features); + // 将文件打包成 ZIP + CreateZipFromShapefiles(shpFilePath, shpFilePathzip); } return response; } - - public async Task UploadExcel1(UploadExcelReq req) + public NetTopologySuite.Geometries.Geometry ParseGeometry(string wkt) { - using (var workbook = new XLWorkbook(req.file.OpenReadStream())) + if (string.IsNullOrEmpty(wkt)) { - string tableName = req.tableName; - var wooksheet = workbook.Worksheet(1); - IXLRows row = wooksheet.RowsUsed(); - List rowCells = row.ToList(); - IXLRow row1 = rowCells[0]; - IXLCells cells = row1.CellsUsed(); - - var cols = new string[cells.Count()]; - - List listTableInfo = new List(); - - int k = 0; - JsonObject json = new JsonObject(); - List> listmap = new List>(); - for (int i = 1; i < rowCells.Count; i++) { - IXLRow rowi = rowCells[i]; - IXLCells cellsi = rowi.CellsUsed(); - Dictionary map = new Dictionary(); - int g = 0; - foreach (IXLCell cell in cellsi) - { - string head = cols[g]; - map.Add(head, cell.Value); - g++; - } - listmap.Add(map); - } - var count = wooksheet.RowCount(); - _client.Insertable(listmap).AS(tableName).ExecuteCommand(); - await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", tableName, ""); - return true; + return null; } + var reader = new WKTReader(); + return reader.Read(wkt); + } + public void ExportToShapefileFour(string shpPath, List features) + { + //var geometryFactory = new GeometryFactory(); + + //// 写入 CPG 文件(定义字符编码) + //var cpgPath = System.IO.Path.ChangeExtension(shpPath, "cpg"); + //File.WriteAllText(cpgPath, "UTF-8", Encoding.UTF8); + //// 获取 SHP 文件头 + //var header = ShapefileDataWriter.GetHeader(features[0], features.Count); + + //// 创建 ShapefileDataWriter + //var shapeFileWriter = new ShapefileDataWriter(shpPath, geometryFactory) + //{ + // Header = header + //}; + + //// 写入 SHP 文件 + //shapeFileWriter.Write(features); + + // 写入 CPG 文件(定义字符编码) + string prjStr = + @"GEOGCS[""GCS_China_Geodetic_Coordinate_System_2000"",DATUM[""D_China_2000"",SPHEROID[""CGCS2000"",6378137.0,298.257222101]],PRIMEM[""Greenwich"",0.0],UNIT[""Degree"",0.0174532925199433]]"; + var cpgPath = Path.ChangeExtension(shpPath, "prj"); + File.WriteAllText(cpgPath, prjStr, Encoding.UTF8); + + Shapefile.WriteAllFeatures(features, shpPath, encoding: Encoding.UTF8); + } + + public void CreateZipFromShapefiles(string shpPath, string zipPath) + { + var files = new List + { + Path.ChangeExtension(shpPath, "cpg"), + shpPath, + Path.ChangeExtension(shpPath, "shx"), + Path.ChangeExtension(shpPath, "dbf"), + Path.ChangeExtension(shpPath, "prj") + }; + + using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create)) + { + foreach (var file in files) + { + if (File.Exists(file)) + { + zipArchive.CreateEntryFromFile(file, Path.GetFileName(file)); + } + } + } + } + + public async Task UploadExcel1(string tableName, IFormFile file) + { + if (file == null || file.Length == 0) + { + return false; + } + + + try + { + using (var stream = new MemoryStream()) + { + // 将文件复制到内存流 + file.CopyTo(stream); + stream.Position = 0; + + IWorkbook workbook; + if (Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) + { + workbook = new XSSFWorkbook(stream); // 处理 .xlsx 文件 + } + else + { + workbook = new HSSFWorkbook(stream); + } + + // + var sheet = workbook.GetSheetAt(0); + // 获取总行数 + var rowCount = sheet.LastRowNum; + if (rowCount < 1) + { + throw new Exception("没有数据"); + } + var currentRow1 = sheet.GetRow(0); + var cols = new string[currentRow1.LastCellNum]; + for (int i = 0; i < currentRow1.LastCellNum; i++) + { + var cell1 = currentRow1.GetCell(i); + cols[i] = cell1.ToString(); + } + var result = new List(); + List> listmap = new List>(); + // 遍历每一行 + for (int row = 1; row <= rowCount; row++) + { + var currentRow = sheet.GetRow(row); + if (currentRow == null) continue; + Dictionary map = new Dictionary(); + + for (int col = 0; col < currentRow.LastCellNum; col++) + { + string head = cols[col]; + map.Add(head, currentRow.GetCell(col)); + + } + listmap.Add(map); + } + _client.Insertable(listmap).AS(tableName).ExecuteCommand(); + await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", tableName, ""); + // 返回结果 + return true; + } + } + catch (Exception ex) + { + return false; + } } @@ -417,62 +545,693 @@ public class LayerApp : SqlSugarBaseApp public bool UpdateTableData(UpdateTableReq req) { string tableName = req.TableName; - int id = req.Id; + string id = ""; var list = req.list; string sql = "update " + tableName + " set "; string sql1 = ""; - for (int i = 0; i < list.Count; i++) { - var map = list[i]; - sql1 = sql1 + map["name"] + " = " + map["value"] + ","; + string num = ""; + for (int i = 0; i < list.Count; i++) + { + var map = list[i]; + if ("id".Equals(map["name"].ToString().ToLower())) + { + num = map["name"].ToString(); + id = map["value"].ToString(); + continue; + } + if (map["name"].ToString().ToLower().Contains("time")) + { + continue; + } + if (map["value"] != null) + { + sql1 = sql1 + "\"" + map["name"] + "\" = '" + map["value"] + "',"; + } } - var sql2 = sql1.Substring(0,sql1.Length-1)+ " where 1=1 and \"Id\"="+id; + var sql2 = sql1.Substring(0,sql1.Length-1)+ " where 1=1 and \""+num+"\"="+id; _client.Ado.ExecuteCommand(sql + sql2); return true; } + public bool UpdateTableData1(UpdateTableReq req) + { + + string tableName = req.TableName; + string id = ""; + var list = req.list; + string sql = "update " + tableName + " set "; + + string num = ""; + for (int i = 0; i < list.Count; i++) + { + var map = list[i]; + string sql1 = ""; + foreach (KeyValuePair kvp in map) + { + string key = kvp.Key; + object value = kvp.Value; + if ("id".Equals(key.ToString().ToLower())) + { + num = key; + id = value.ToString(); + continue; + } + if (map["name"].ToString().ToLower().Contains("time")) + { + continue; + } + if (value != null) + { + sql1 = sql1 + "\"" + key + "\" = '" + value + "',"; + } + // 处理键值对 + } + var sql2 = sql1.Substring(0, sql1.Length - 1) + " where 1=1 and \"" + num + "\"=" + id; + _client.Ado.ExecuteCommand(sql + sql2); + } + + + return true; + } + + + public async Task UploadExcel2(string tableName, IFormFile file) + { + if (file == null || file.Length == 0) + { + return false; + } + + + try + { + using (var stream = new MemoryStream()) + { + // 将文件复制到内存流 + file.CopyTo(stream); + stream.Position = 0; + + IWorkbook workbook; + if (Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) + { + workbook = new XSSFWorkbook(stream); // 处理 .xlsx 文件 + } + else + { + workbook = new HSSFWorkbook(stream); + } + + // + var sheet = workbook.GetSheetAt(0); + // 获取总行数 + var rowCount = sheet.LastRowNum; + if (rowCount < 1) + { + throw new Exception("没有数据"); + } + var currentRow1 = sheet.GetRow(0); + var cols = new string[currentRow1.LastCellNum]; + for (int i = 0; i < currentRow1.LastCellNum; i++) + { + var cell1 = currentRow1.GetCell(i); + cols[i] = cell1.ToString(); + } + var result = new List(); + List> listmap = new List>(); + // 遍历每一行 + for (int row = 1; row <= rowCount; row++) + { + var currentRow = sheet.GetRow(row); + if (currentRow == null) continue; + Dictionary map = new Dictionary(); + + for (int col = 0; col < currentRow.LastCellNum; col++) + { + string head = cols[col]; + map.Add(head, currentRow.GetCell(col)); + + } + listmap.Add(map); + } + _client.Insertable(listmap).AS(tableName).ExecuteCommand(); + + // 返回结果 + return true; + } + } + catch (Exception ex) + { + return false; + } + + } + [HttpPost] public async Task AddUploadExcel(UploadExcelReq req) { - - using (var workbook = new XLWorkbook(req.file.OpenReadStream())) + + if (req.file == null || req.file.Length == 0) { - - string sql = $"delete from " + req.tableName; - _client.Ado.ExecuteCommand(sql); - string tableName = req.tableName; - var wooksheet = workbook.Worksheet(1); - IXLRows row = wooksheet.RowsUsed(); - List rowCells = row.ToList(); - IXLRow row1 = rowCells[0]; - IXLCells cells = row1.CellsUsed(); - - var cols = new string[cells.Count()]; - - List listTableInfo = new List(); - - int k = 0; - JsonObject json = new JsonObject(); - List> listmap = new List>(); - for (int i = 1; i < rowCells.Count; i++) - { - IXLRow rowi = rowCells[i]; - IXLCells cellsi = rowi.CellsUsed(); - Dictionary map = new Dictionary(); - int g = 0; - foreach (IXLCell cell in cellsi) - { - string head = cols[g]; - map.Add(head, cell.Value); - g++; - } - listmap.Add(map); - } - var count = wooksheet.RowCount(); - _client.Insertable(listmap).AS(tableName).ExecuteCommand(); - await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", tableName, ""); - return true; + return false; } + try + { + using (var stream = new MemoryStream()) + { + // 将文件复制到内存流 + req.file.CopyTo(stream); + stream.Position = 0; + + IWorkbook workbook; + if (Path.GetExtension(req.file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) + { + workbook = new XSSFWorkbook(stream); // 处理 .xlsx 文件 + } + else + { + workbook = new HSSFWorkbook(stream); + } + + // + var sheet = workbook.GetSheetAt(0); + // 获取总行数 + var rowCount = sheet.LastRowNum; + if (rowCount < 1) + { + throw new Exception("没有数据"); + } + var currentRow1 = sheet.GetRow(0); + var cols = new string[currentRow1.LastCellNum]; + for (int i = 0; i < currentRow1.LastCellNum; i++) + { + var cell1 = currentRow1.GetCell(i); + cols[i] = cell1.ToString(); + } + var result = new List(); + List> listmap = new List>(); + // 遍历每一行 + for (int row = 1; row <= rowCount; row++) + { + var currentRow = sheet.GetRow(row); + if (currentRow == null) continue; + Dictionary map = new Dictionary(); + + for (int col = 0; col < currentRow.LastCellNum; col++) + { + string head = cols[col]; + map.Add(head, currentRow.GetCell(col)); + + } + listmap.Add(map); + } + _client.Insertable(listmap).AS(req.tableName).ExecuteCommand(); + //await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", req.tableName, ""); + // 返回结果 + return true; + } + } + catch (Exception ex) + { + return false; + } + } + public async Task> uploadSldStyle(string styleName, string tablename,string filepath) + { + Response response = new Response(); + var flag = await GeoUtil.ExistStyle("", styleName); + if (flag) { + response.Message = "样式已存在"; + response.Result = false; + return response; + } + var sldpath = Path.Combine(_filePath, filepath); + var flag1 = await GeoUtil.PublishSldStyle(sldpath, styleName); + await GeoUtil.UpdateStyle("", tablename, styleName); + if (flag1) + { + response.Message = "发布成功"; + response.Result = flag1; + return response; + } + else { + response.Message = "发布失败"; + response.Result = false; + return response; + } + } + public async Task> UploadShape2(string zipFilePath, string tableName + ) + { + try + { + string sq2 = "delete from " + tableName; + _client.Ado.ExecuteCommand(sq2); + string srd = ""; + using var db = Repository.AsSugarClient(); + // 开启事务 + + // 取得文件完全路径 + zipFilePath = Path.Combine(_filePath, zipFilePath); + // 确保ZIP文件存在 + if (!File.Exists(zipFilePath)) + { + throw new FileNotFoundException("ZIP文件未找到。"); + } + + + // 打开ZIP存档 取除后缀之前的字符串 + var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) + + "extract"; + // 解压文件 + await UnZip(zipFilePath, extractPath); + var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名 + var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories); + if (fileName.IsEmpty()) + { + throw new Exception("压缩文件中无shp文件"); + } + + var shpFileName = fileName[0]; + var shpFile = Path.Combine(extractPath, shpFileName); + using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default)) + { + + var dbfReader = dataReader.DbaseHeader; + List headlist = new List(); + foreach (var dbaseFieldDescriptor in dbfReader.Fields) + { + headlist.Add(dbaseFieldDescriptor.Name); + + } + + Console.WriteLine("记录数" + dataReader.RecordCount); + //throw new Exception("失败"); + var objs = new List>(1001); + var num = 0; + int count = 0; + while (dataReader.Read()) + { + count++; + Console.WriteLine("记录行:" + count); + var insertObj = new Dictionary(); + // 读取列 + for (int i = 0; i < dataReader.FieldCount; i++) + { + var colName = dataReader.GetName(i); + + for (int k = 0; k < headlist.Count; k++) { + var header = headlist[k]; + if (colName.ToLower().Contains("time")) + { + break; + } + if (colName.ToLower().Equals("geometry")) + { + var geometry = (NetTopologySuite.Geometries.Geometry)dataReader.GetValue(i); + + var geometryForWgs84 = GeometryFactory.Default.WithSRID(4326) + .CreateGeometry(geometry); + insertObj.Add("geom", geometryForWgs84.AsText()); + break; + } + if (header.Equals(colName)) + { + + + insertObj.Add(header, dataReader.GetValue(i)); + break; + } + + } + + } + + objs.Add(insertObj); + if (num++ == 999) + { + await db.Insertable(objs) + .AS(tableName) // 指定目标表名 + .ExecuteCommandAsync(); + num = 0; + objs.Clear(); + } + } + + // 读取末尾 + await db.Insertable(objs) + .AS(tableName) // 指定目标表名 + .ExecuteCommandAsync(); + } + + await db.Ado.CommitTranAsync(); + } + catch (Exception ex) + { + throw new CommonException(ex.Message, 500); + } + + return new Response + { + Result = true + }; + } + + public async Task> UploadShape3(string zipFilePath, string tableName + ) + { + try + { + + string srd = ""; + using var db = Repository.AsSugarClient(); + // 开启事务 + + // 取得文件完全路径 + zipFilePath = Path.Combine(_filePath, zipFilePath); + // 确保ZIP文件存在 + if (!File.Exists(zipFilePath)) + { + throw new FileNotFoundException("ZIP文件未找到。"); + } + + + // 打开ZIP存档 取除后缀之前的字符串 + var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) + + "extract"; + // 解压文件 + await UnZip(zipFilePath, extractPath); + var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名 + var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories); + if (fileName.IsEmpty()) + { + throw new Exception("压缩文件中无shp文件"); + } + + var shpFileName = fileName[0]; + var shpFile = Path.Combine(extractPath, shpFileName); + using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default)) + { + + var dbfReader = dataReader.DbaseHeader; + List headlist = new List(); + foreach (var dbaseFieldDescriptor in dbfReader.Fields) + { + headlist.Add(dbaseFieldDescriptor.Name); + + } + + Console.WriteLine("记录数" + dataReader.RecordCount); + //throw new Exception("失败"); + var objs = new List>(1001); + var num = 0; + int count = 0; + while (dataReader.Read()) + { + count++; + Console.WriteLine("记录行:" + count); + var insertObj = new Dictionary(); + // 读取列 + for (int i = 0; i < dataReader.FieldCount; i++) + { + var colName = dataReader.GetName(i); + + for (int k = 0; k < headlist.Count; k++) + { + var header = headlist[k]; + if (colName.ToLower().Contains("time")) + { + break; + } + if (colName.ToLower().Equals("geometry")) + { + var geometry = (NetTopologySuite.Geometries.Geometry)dataReader.GetValue(i); + + var geometryForWgs84 = GeometryFactory.Default.WithSRID(4326) + .CreateGeometry(geometry); + insertObj.Add("geom", geometryForWgs84.AsText()); + break; + } + if (header.Equals(colName)) + { + + + insertObj.Add(header, dataReader.GetValue(i)); + break; + } + + } + + } + + objs.Add(insertObj); + if (num++ == 999) + { + await db.Insertable(objs) + .AS(tableName) // 指定目标表名 + .ExecuteCommandAsync(); + num = 0; + objs.Clear(); + } + } + + // 读取末尾 + await db.Insertable(objs) + .AS(tableName) // 指定目标表名 + .ExecuteCommandAsync(); + } + + await db.Ado.CommitTranAsync(); + await GeoUtil.CreateStoreAndLayer("", "EPSG:4326", tableName, ""); + } + catch (Exception ex) + { + throw new CommonException(ex.Message, 500); + } + + return new Response + { + Result = true + }; + } + private static async Task UnZip(string zipFilePath, string extractPath) + { + await Task.Run(() => + { + Directory.CreateDirectory(extractPath); + // 设置字符编码 + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + var gbk = Encoding.GetEncoding("utf-8"); + using (var archive = ZipFile.OpenRead(zipFilePath)) + { + // 列举ZIP文件中的条目 + foreach (var entry in archive.Entries) + { + var xxx = gbk.GetString(Encoding.Default.GetBytes(entry.FullName)); + Console.WriteLine(xxx); + } + + // 提取ZIP文件中的所有文件到指定目录 + + foreach (var entry in archive.Entries) + { + if (entry.Name != string.Empty) + { + // 确保完整路径存在 entry.FullName 是否可以编码 + var fixedEntryName = entry.FullName.Replace("/", ""); + var destinationPath = Path.GetFullPath(Path.Combine(extractPath, fixedEntryName)); + Console.WriteLine("解压文件路径:" + destinationPath); + if (!destinationPath.StartsWith(Path.GetFullPath(extractPath) + Path.DirectorySeparatorChar)) + { + throw new UnauthorizedAccessException("试图提取的文件超出了目标文件夹的路径边界。"); + } + + // 提取条目到目标路径 + entry.ExtractToFile(destinationPath, overwrite: true); + } + } + } + + // 遍历解压目录,是否有shp后缀的文件 + if (!Directory.Exists(extractPath)) + { + throw new Exception("文件解压失败"); + } + }); + } + public async Task>> UploadShape1(string zipFilePath, string tableName + ) + { + try + { + + string srd = ""; + using var db = Repository.AsSugarClient(); + // 开启事务 + + // 取得文件完全路径 + zipFilePath = Path.Combine(_filePath, zipFilePath); + // 确保ZIP文件存在 + if (!File.Exists(zipFilePath)) + { + throw new FileNotFoundException("ZIP文件未找到。"); + } + + + // 打开ZIP存档 取除后缀之前的字符串 + var extractPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf(".", StringComparison.Ordinal)) + + "extract"; + // 解压文件 + await UnZip(zipFilePath, extractPath); + var searchPattern = "*.shp"; // 设置你想要遍历的文件后缀名 + var fileName = Directory.GetFiles(extractPath, searchPattern, SearchOption.AllDirectories); + if (fileName.IsEmpty()) + { + throw new Exception("压缩文件中无shp文件"); + } + + var shpFileName = fileName[0]; + var shpFile = Path.Combine(extractPath, shpFileName); + List dynamics = new List(); + List> dicts = new List>(); + using (var dataReader = new ShapefileDataReader(shpFile, GeometryFactory.Default)) + { + + var dbfReader = dataReader.DbaseHeader; + List headlist = new List(); + foreach (var dbaseFieldDescriptor in dbfReader.Fields) + { + headlist.Add(dbaseFieldDescriptor.Name); + + } + + Console.WriteLine("记录数" + dataReader.RecordCount); + //throw new Exception("失败"); + var objs = new List>(1001); + var num = 0; + int count = 0; + + while (dataReader.Read()) + { + count++; + Console.WriteLine("记录行:" + count); + var insertObj = new Dictionary(); + // 读取列 + Dictionary dict = new Dictionary(); + // 读取列 + var flag = false; + for (int i = 0; i < dataReader.FieldCount; i++) + { + var colName = dataReader.GetName(i); + if (colName.ToLower().Equals("geometry")) + { + var geometry = (NetTopologySuite.Geometries.Geometry)dataReader.GetValue(i); + + var geometryForWgs84 = GeometryFactory.Default.WithSRID(4326) + .CreateGeometry(geometry); + string sql = $"select column_name as name from INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'public' AND table_name ='" + tableName + "'"; + + var cloumnlist = _client.Ado.SqlQuery(sql); + + string names = ""; + string geoms = ""; + for (int l = 0; l < cloumnlist.Count; l++) + { + var name = cloumnlist[l]; + if (name.Contains("geom")) + { + geoms = name; + + } + else + { + + names = names + "\"" + name + "\","; + } + } + string sql1 = $"select " + names + "ST_AsText(" + geoms + ") as " + geoms + $" from " + tableName + " where geom='" + geometryForWgs84.AsText() + "'"; + + var obj = _client.Ado.SqlQuerySingle(sql1); + if (obj!=null) + { + dynamics.Add(obj); + dict.Add("geom", geometryForWgs84.AsText()); + flag = true; + } + + } + else { + dict.Add(colName, dataReader.GetValue(i)); + } + for (int k = 0; k < headlist.Count; k++) + { + var header = headlist[k]; + if (colName.ToLower().Contains("time")) + { + break; + } + if (colName.ToLower().Equals("geometry")) + { + var geometry = (NetTopologySuite.Geometries.Geometry)dataReader.GetValue(i); + + var geometryForWgs84 = GeometryFactory.Default.WithSRID(4326) + .CreateGeometry(geometry); + insertObj.Add("geom", geometryForWgs84.AsText()); + break; + } + if (header.Equals(colName)) + { + + + insertObj.Add(header, dataReader.GetValue(i)); + break; + } + + } + + } + if (flag) + { + dicts.Add(dict); + continue; + } + objs.Add(insertObj); + if (num++ == 999) + { + await db.Insertable(objs) + .AS(tableName) // 指定目标表名 + .ExecuteCommandAsync(); + num = 0; + objs.Clear(); + } + } + + // 读取末尾 + await db.Insertable(objs) + .AS(tableName) // 指定目标表名 + .ExecuteCommandAsync(); + + } + + await db.Ado.CommitTranAsync(); + Dictionary res = new Dictionary(); + res.Add("nowData", dicts); + res.Add("originData", dynamics); + return new Response> + { + Result = res + }; + + } + catch (Exception ex) + { + throw new CommonException(ex.Message, 500); + } + + + } + + } \ No newline at end of file diff --git a/OpenAuth.WebApi/Controllers/ServiceControllers/DataMaintenance/LayerController.cs b/OpenAuth.WebApi/Controllers/ServiceControllers/DataMaintenance/LayerController.cs index 3036a9a..77080dc 100644 --- a/OpenAuth.WebApi/Controllers/ServiceControllers/DataMaintenance/LayerController.cs +++ b/OpenAuth.WebApi/Controllers/ServiceControllers/DataMaintenance/LayerController.cs @@ -5,6 +5,7 @@ using OpenAuth.App; using OpenAuth.App.Request; using OpenAuth.App.ServiceApp.LayerManagerApp; using OpenAuth.App.ServiceApp.LayerManagerApp.Request; +using Org.BouncyCastle.Ocsp; namespace OpenAuth.WebApi.Controllers.ServiceControllers.DataMaintenance; @@ -39,9 +40,10 @@ public class LayerController : ControllerBase /// /// [HttpPost] - public async Task> UploadShape(LayerReq req) + [AllowAnonymous] + public async Task> UploadShape(string zipFilePath, string tableName) { - return await _app.UploadShape(req); + return await _app.UploadShape3( zipFilePath, tableName); } [HttpGet] @@ -52,34 +54,73 @@ public class LayerController : ControllerBase [HttpGet] [AllowAnonymous] - public IActionResult TempeleteByTableName(string tablename) + public IActionResult TempeleteByTableName(string tablename,int type) { var res = new Response(); - var excelRes = _app.TempeleteByTableName(tablename); - if (excelRes.Code == 200) + if (type ==0) { - return File(excelRes.Result.ToArray(), - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "数据导出" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); + var excelRes = _app.TempeleteByTableName(tablename,type,"",""); + if (excelRes.Code == 200) + { + return File(excelRes.Result.ToArray(), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "数据导出" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); + } + else + { + res.Code = excelRes.Code; + res.Message = "导出失败"; + } } - else + if (type==1) { - res.Code = excelRes.Code; - res.Message = "导出失败"; + try + { + string shpFilePath = Path.Combine(Path.GetTempPath(), $"图斑信息{DateTime.Now:yyyyMMddHHmmss}.shp"); + string shpFilePathzip = Path.Combine(Path.GetTempPath(), $"图斑信息{DateTime.Now:yyyyMMddHHmmss}.zip"); + _app.TempeleteByTableName(tablename,type, shpFilePath, shpFilePathzip); + byte[] fileBytes = System.IO.File.ReadAllBytes(shpFilePathzip); + return File(fileBytes, "application/octet-stream", $"图斑信息{DateTime.Now:yyyyMMddHHmmss}.zip"); + } + catch (Exception ex) + { + return StatusCode(500, $"Internal server error: {ex.Message}"); + } } + return Ok(res); } + [HttpPost] [AllowAnonymous] - public async Task> UploadExcelAll([FromBody]UploadExcelReq req) + public async Task> UploadExcelAll(string tableName, IFormFile file) { Response response = new Response(); try { - response.Result = await _app.UploadExcel1(req); + response.Result = await _app.UploadExcel1(tableName, file); + } + catch (Exception ex) + { + response.Code = 500; + response.Message = ex.InnerException?.Message ?? ex.Message; + } + return response; + } + + + [HttpPost] + [AllowAnonymous] + public async Task> UploadExcelInsert(string tableName, IFormFile file) + { + + Response response = new Response(); + try + { + response.Result = await _app.UploadExcel2(tableName, file); } catch (Exception ex) { @@ -111,9 +152,9 @@ public class LayerController : ControllerBase [HttpPost] [AllowAnonymous] - public async Task> AddUploadExcel([FromBody] UploadExcelReq req) + public async Task> AddUploadExcel(string tableName, IFormFile file) { - + UploadExcelReq req = new UploadExcelReq { tableName = tableName, file = file }; Response response = new Response(); try { @@ -127,4 +168,54 @@ public class LayerController : ControllerBase return response; } + [HttpGet] + [AllowAnonymous] + public async Task> UploadSldStyle(string tablename,string styleName, string filepath) + { + + Response response = new Response(); + try + { + var result = await _app.uploadSldStyle(styleName,tablename, filepath); + return result; + } + catch (Exception ex) + { + response.Code = 500; + response.Message = ex.InnerException?.Message ?? ex.Message; + response.Result = false; + } + return response; + } + /// + [HttpPost] + [AllowAnonymous] + public async Task>> UploadShape1(string zipFilePath, string tableName) + { + return await _app.UploadShape1(zipFilePath,tableName); + } + [HttpPost] + [AllowAnonymous] + public async Task> UploadShape2(string zipFilePath, string tableName) + { + return await _app.UploadShape2(zipFilePath, tableName); + } + [HttpPost] + [AllowAnonymous] + public Response UpdateTableOriginalData(UpdateTableReq req) + { + + Response response = new Response(); + try + { + response.Result = _app.UpdateTableData1(req); + } + catch (Exception ex) + { + response.Code = 500; + response.Message = ex.InnerException?.Message ?? ex.Message; + } + return response; + } + } \ No newline at end of file diff --git a/OpenAuth.WebApi/appsettings.json b/OpenAuth.WebApi/appsettings.json index 3438301..c9485ca 100644 --- a/OpenAuth.WebApi/appsettings.json +++ b/OpenAuth.WebApi/appsettings.json @@ -57,7 +57,7 @@ //"AppSecret": "8f4ba2bf57c360d5b77751fc8a82701b" }, "GeoServer": { - "GeoserverUrl": "http://192.168.10.141:8080/geoserver", + "GeoserverUrl": "http://192.168.10.163:8080/geoserver", "JobwebUrl": "http://192.168.10.125:9023/", "Workspace": "my_workspace", "Username": "admin",