using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Threading; using System.Net; using Lskj.Control; using System.Threading.Tasks; using Lskj.Core; using DevExpress.XtraGrid.Columns; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using Lskj.Model; using Lskj.Control.BrowserSetting; using Lskj.Business; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using Lskj.Business.Impl; using System.Text.RegularExpressions; using Lskj.Util; using System.Web; using Lskj.Control.Model; using System.Data.SqlClient; namespace Lskj.PubBomImportNew { /// /// 下载进度窗口 /// public partial class FrmProgress : Form { public FrmMain frmMain; public DynamicBomImportNew Model; public System.Windows.Forms.Timer ImportTimer = new System.Windows.Forms.Timer(); public FrmProgress() { InitializeComponent(); this.ControlBox = false; } /// /// bom结构上传(总部) /// /// public void StartImportInFileByZB(List selectRows) { //try //{ // if (Directory.Exists("BomImportTemp")) // { // Directory.Delete("BomImportTemp", true); // } // Directory.CreateDirectory("BomImportTemp"); // int execOrder = 1; // if (selectRows.Count > 1) // { // throw new Exception($"不允许选择多个文件"); // } // DataRow mxRow = selectRows[0]; // if (mxRow != null) // { // string mxDirPath = mxRow["BomFieldNameDir"] + ""; // string productId = mxRow["BomMxMainProduct"] + ""; // string addState = mxRow["BomMxAddState"] + ""; // if (string.IsNullOrEmpty(Model.MainFieldDic)) // { // throw new Exception($"字段对应关系配置异常"); // } // if (string.IsNullOrEmpty(productId)) // { // throw new Exception($"保存失败\r\n请重新进行BOM上传后保存"); // } // if (addState.Equals("新增")) // { // DataRow billRow = BaseImpl.GetDataRowResult($"select qms_maddf_billdocument_id from qms_BillFileAddMaintab where qms_maddf_productid = '{productId}' and isnull(qms_maddf_addMode,'0') = '0'"); // if (billRow != null) // { // throw new Exception($"物料编码{productId}的BOM新增单已存在审批流\r\n请进行审批"); // } // DataRow billbomRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}'"); // if (billRow != null) // { // throw new Exception($"物料编码{productId}的BOM建立单已存在\r\n请进行修改操作"); // } // } // else // { // DataRow billbomRow = BaseImpl.GetDataRowResult($"select top 1 billdocument_id from bom_BillTab where productid='{productId}' and stepover = '1'"); // if (billbomRow != null) // { // throw new Exception($"物料编码{productId}的BOM建立单已终审\r\n禁止修改操作"); // } // } // FileInfo mxInfo = null; // if (!string.IsNullOrEmpty(mxDirPath)) // { // mxInfo = new FileInfo(mxDirPath); // } // if (mxInfo != null) // { // DataTable mxfiletable = BaseImpl.GetDataTableResult($"select sname,fileId,webpath from p_fm_filetab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{productId}' and dllcoid = '1000202') and speciesno = '010106' and sname = '{mxInfo.Name}'"); // if (mxfiletable.Rows.Count > 0) // { // throw new Exception($"该文件已存在,请确认后再创建BOM"); // } // int.TryParse(Model.FirstRowIndex + "", out int firstRowIndex); // DataTable parentTable = ExcelToDatatable(mxInfo.FullName, Model, Model.SheetName, firstRowIndex); // parentTable = parentTable.Rows.Cast().Where(n => int.TryParse(n["序号"] + "", out _) && !string.IsNullOrEmpty(n["物料编码"] + "")).ToList().CopyToDataTable(); // //StringBuilder stringBuilder = new StringBuilder(); // //foreach (DataRow dataRow in parentTable.Rows) // //{ // // string code = (dataRow["图号"] + "").Trim(); // // if (code.StartsWith("QD")) // // { // // int createCode = ProductSaveUnique(code.Replace("'", "''"), (dataRow["名称"] + "").Replace("'", "''"), (dataRow["备注"] + "").Replace("'", "''"), "1000202_1", out string pid, out string msg); // // if ((createCode + "").Equals("-1")) // // { // // throw new Exception($"虚拟物料创建失败\r\n{msg}"); // // } // // } // //} // //if (!string.IsNullOrEmpty(stringBuilder.ToString())) // //{ // // SqlHelper.ExecuteNonQuery(stringBuilder.ToString()); // //} // frmBillInfo.OnControlSourceBind += (s, args) => // { // Task task = new Task(() => // { // try // { // int.TryParse(Model.FirstRowIndex, out int index); // frmMain.FirstRowIndex = index; // bool isUpload = false; // string msg = ""; // Dictionary maxBcFileDic = new Dictionary(); // Dictionary fileTableDic = new Dictionary(); // #region 新增或修改MX // frmBillInfo.OnBillAdd(); // SetProcessBar(0, 0); // SetProcessMsg($"正在导入:{Path.GetFileName(mxInfo.FullName)}"); // DataTable childTable = frmBillInfo.GcMainView.GridControl.DataSourceTable().Clone(); // var mxCodeRows = parentTable.AsEnumerable(); // string[] fieldDic = Model.MainFieldDic.Split(','); // foreach (DataRow parentRow in parentTable.Rows) // { // string code = (parentRow["物料编码"] + "").Trim(); // int codeCount = mxCodeRows.Where(n => (n["物料编码"] + "").Trim().StartsWith(code)).Count(); // if (codeCount > 1)//只允许存在一个 // { // throw new Exception($"文件中的物料编码{code}重复,请修改"); // } // DataRow childRow = childTable.NewRow(); // foreach (string item in fieldDic) // { // string[] fieldArray = item.Split('^'); // string key0 = fieldArray[0]; // string key1 = fieldArray[1]; // childRow[key0] = parentRow[key1] + ""; // } // //childRow["ProductId"] = parentRow["物料编码"] + ""; // //childRow["appellation"] = parentRow["名称"] + ""; // //childRow["bak"] = parentRow["备注"] + ""; // //childRow["tamount"] = parentRow["数量"] + ""; // //childRow["amount"] = parentRow["数量"] + ""; // childTable.Rows.Add(childRow); // } // SetProcessBar(20, 0); // if (childTable.Rows.Count == 0) // { // throw new Exception($"明细数据不能空"); // } // SetProcessBar(40, 0); // string billMasterSql = $"select (select top 1 billdocument_id from bom_BillTab where productid='{productId}') as billdocument_id,'0' affirmer,'0' rtagid,'{productId}' as productid,'' as bak,'' as bombb,'' as bombc"; // // 处理单据表头数据 // DataRow masterRow = BillImpl.GetDataRowResult(billMasterSql); // SetProcessBar(60, 0); // frmBillInfo.AddOrUpdateBill(masterRow, childTable); // string guid = Guid.NewGuid() + ""; // frmBillInfo.BillSaveSql(guid); // SetProcessBar(80, 0); // //上传文件 // string uploadMxFileId = ""; // if (mxfiletable.Rows.Count == 0) // { // isUpload = UploadFileToAudit(mxInfo.FullName, productId, "010106", out msg, out uploadMxFileId); // if (!isUpload) // { // throw new Exception($"{mxInfo.Name}附件上传失败\r\n{msg}"); // } // } // StaticControl.RightMenuGridView.GridControl.Invoke(new Action(() => // { // if (mxRow.Table.Columns.Contains("qms_laddf_FileId")) // { // int.TryParse(uploadMxFileId, out int qms_laddf_FileId); // mxRow["qms_laddf_FileId"] = qms_laddf_FileId; // } // if (mxRow.Table.Columns.Contains("qms_laddf_Exec")) // { // mxRow["qms_laddf_Exec"] = guid; // } // if (mxRow.Table.Columns.Contains("qms_laddf_ExecOrder")) // { // mxRow["qms_laddf_ExecOrder"] = execOrder; // } // })); // execOrder += 1; // #endregion // SetProcessBar(100, (1 / (parentTable.Rows.Count + 1)) * 100); // SetProcessLabelAllMsg($"总进度:{1}/{parentTable.Rows.Count + 1}"); // this.Invoke(new Action(() => // { // this.DialogResult = DialogResult.OK; // Close(); // ImportTimer?.Dispose(); // })); // } // catch (Exception ex) // { // MessageUtil.Show(ex.Message); // this.Invoke(new Action(() => // { // this.DialogResult = DialogResult.Cancel; // Close(); // ImportTimer?.Dispose(); // })); // } // }); // task.Start(); // }; // frmBillInfo.OnLoad(Model); // frmMain.ParentView = frmBillInfo.GcMainView; // } // else // { // throw new Exception("文件不存在"); // } // } //} //catch (Exception ex) //{ // MessageUtil.Show(ex.Message); // this.Invoke(new Action(() => // { // this.DialogResult = DialogResult.Cancel; // Close(); // ImportTimer?.Dispose(); // })); //} } public int ProductSaveUnique(string spec, string appellation, string bak, string billSeq, out string productId, out string tipMsg) { productId = string.Empty; tipMsg = string.Empty; try { /*---------------------------------------------------- * 1) 组装存储过程参数 *--------------------------------------------------*/ // ProductId OUTPUT SqlParameter pProductId = new SqlParameter("@ProductId", SqlDbType.VarChar, 100) { Direction = ParameterDirection.Output }; // 存储过程 RETURN 值 SqlParameter pReturn = new SqlParameter("@return", SqlDbType.Int) { Direction = ParameterDirection.ReturnValue }; // 中文字段可根据服务器排序规则切换参数类型 bool useNVar = ERPInfo.Instance.ChangeParameterType; SqlParameter[] param = { new SqlParameter("@Spec", SqlDbType.VarChar, 50), useNVar ? new SqlParameter("@Appellation", SqlDbType.NVarChar, 200) : new SqlParameter("@Appellation", SqlDbType.VarChar, 200), useNVar ? new SqlParameter("@Bak", SqlDbType.NVarChar, 200) : new SqlParameter("@Bak", SqlDbType.VarChar, 200), new SqlParameter("@BillSeq", SqlDbType.VarChar, 40), pProductId, pReturn }; param[0].Value = spec; param[1].Value = appellation ?? string.Empty; param[2].Value = bak ?? string.Empty; param[3].Value = string.IsNullOrWhiteSpace(billSeq) ? (object)DBNull.Value : billSeq; SqlHelper.ExecuteNonQuery( CommandType.StoredProcedure, "sp_InsertProductUnique", param); /*---------------------------------------------------- * 3) 处理返回值与提示信息 *--------------------------------------------------*/ productId = pProductId.Value == DBNull.Value ? string.Empty : pProductId.Value.ToString(); int retCode = (pReturn.Value == DBNull.Value) ? -1 : Convert.ToInt32(pReturn.Value); // 根据返回值给出业务提示 switch (retCode) { case 0: tipMsg = "保存成功!"; break; case 1: tipMsg = "规格已存在,直接返回现有编码。"; break; default: tipMsg = "发生异常,请查看日志!"; break; } return retCode; } catch (Exception ex) { tipMsg = ex.Message; throw; // 继续向外抛,让调用层捕获日志 } } /// /// 显示当前文件 /// /// private void SetProcessMsg(string text) { this.labelCurrentItem.Invoke(new Action(() => { this.labelCurrentItem.Text = text; })); } private void SetProcessLabelAllMsg(string text) { this.lblAll.Invoke(new Action(() => { this.lblAll.Text = text; })); } /// /// 显示当前进度 /// /// /// private void SetProcessBar(int current, int total) { this.Invoke(new Action(() => { this.progressBarCurrent.Value = current; this.progressBarTotal.Value = total; })); } /// /// 获取表格数据 /// /// /// /// /// public DataTable ExcelToDatatable(string fileName, DynamicBomImportNew Model, string sheetName = "", int firstRowIndex = 0) { DataTable data = new DataTable(); FileStream fs; IWorkbook workbook = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 { workbook = new XSSFWorkbook(fs); } else if (fileName.IndexOf(".xls") > 0) // 2003版本 { workbook = new HSSFWorkbook(fs); } ISheet sheet; if (!string.IsNullOrEmpty(sheetName)) { sheet = workbook.GetSheet(sheetName);//根据给定的sheet名称获取数据 } else { //也可以根据sheet编号来获取数据 sheet = workbook.GetSheetAt(0);//获取第几个sheet表(此处表示如果没有给定sheet名称,默认是第一个sheet表) } if (sheet != null) { int startRow = firstRowIndex + 1; IRow firstRow = sheet.GetRow(firstRowIndex); IRow bandRow = null; int cellCount = firstRow.LastCellNum; for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)//第一行列数循环 { ICell titleCell = firstRow.GetCell(i); ICell bandCell = null; bool isBandTitle = false; if (titleCell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, firstRowIndex, i); startRow = mergrRange.LastRow + 1; if (mergrRange != null) { if (mergrRange.FirstColumn < mergrRange.LastColumn)//&& !Model.CustomerServiceApp { isBandTitle = true; bandRow = sheet.GetRow(mergrRange.LastRow + 1); titleCell = firstRow.GetCell(mergrRange.FirstColumn); bandCell = bandRow.GetCell(i); CellRangeAddress bandMergrRange = FindMergedRegion(sheet, mergrRange.LastRow + 1, i); if (bandMergrRange != null) { startRow = bandMergrRange.LastRow + 1; } else { startRow = mergrRange.LastRow + 2; } } else { startRow = mergrRange.LastRow + 1; } } } string fieldName = ""; if (!isBandTitle || bandRow == null) { fieldName = GetCellValue(titleCell); } else { fieldName = $"{GetCellValue(titleCell)}|{GetCellValue(bandCell)}"; } if (string.IsNullOrEmpty(fieldName) && titleCell.IsMergedCell) { cellCount -= 1; continue; } DataColumn column = new DataColumn(fieldName);//获取标题 data.Columns.Add(column);//添加列 } //最后一行的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; i++)//循环遍历所有行 { IRow row = sheet.GetRow(i);//第几行 if (row == null) { continue; //没有数据的行默认是null; } //将excel表每一行的数据添加到datatable的行中 DataRow dataRow = data.NewRow(); int dataRowIndex = 0; for (int j = firstRow.FirstCellNum; j < cellCount; j++) { ICell cell = row.GetCell(j); if (cell != null && cell.IsMergedCell) { CellRangeAddress mergrRange = FindMergedRegion(sheet, i, j); if (j == mergrRange.FirstColumn) { dataRow[dataRowIndex] = GetCellValue(row.GetCell(j)); dataRowIndex += 1; } else { cellCount += 1; continue; } } else { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null { dataRow[dataRowIndex] = GetCellValue(row.GetCell(j)); dataRowIndex += 1; } } } data.Rows.Add(dataRow); } } return data; } catch (IOException ex) { throw new IOException(string.Format("读取模板内容失败,原因:{0}", ex.Message)); } catch (Exception ex) { throw new Exception(string.Format("读取模板内容失败,原因:{0}", ex.Message)); } } /// /// 获取单元格值 /// /// /// public static string GetCellValue(ICell cell) { string cellValue = ""; try { if (cell != null) { // 根据单元格类型获取值 switch (cell.CellType) { case CellType.String: cellValue = cell.StringCellValue; break; case CellType.Numeric: cellValue = cell.NumericCellValue.ToString(); break; case CellType.Boolean: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.Formula://单元格中带有公式,根据类型继续判断 switch (cell.CachedFormulaResultType) { case CellType.String: cellValue = cell.StringCellValue; break; case CellType.Numeric: cellValue = cell.NumericCellValue.ToString(); break; case CellType.Boolean: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.Blank: break; default: cellValue.ToString(); break; } break; default: cellValue = cell.ToString(); break; } } } catch (Exception) { } return cellValue; } /// /// 获取合并区域 /// /// /// /// /// private CellRangeAddress FindMergedRegion(ISheet sheet, int rowIndex, int columnIndex) { int mergedRegionsCount = sheet.NumMergedRegions; for (int i = 0; i < mergedRegionsCount; i++) { CellRangeAddress mergedRegion = sheet.GetMergedRegion(i); if (mergedRegion.IsInRange(rowIndex, columnIndex)) { return mergedRegion; // 返回合并区域 } } return null; // 未找到合并区域 } /// /// 上传文件 /// /// /// /// private bool UploadFile(string filePath, string idValue, out string msg, out string outFileId) { bool isUpload = false; string File = filePath; string returnMsg = ""; string fileId = ""; string postUrl = ""; try { //获取文件信息 FileInfo fileInfo = new FileInfo(File); string suffix = Path.GetExtension(File); string name = fileInfo.Name; DateTime creationTime = fileInfo.CreationTime; byte[] fileBytes = ConvertFileToBytes(File); string fileStream = Convert.ToBase64String(fileBytes); string userId = ERPInfo.Instance.UserId; DateTime uploadTime = DateTime.Now; string speciesno = "010102"; // 检查扩展名是否为 .xlsx 或 .xls if (suffix.Equals(".xlsx", StringComparison.OrdinalIgnoreCase) || suffix.Equals(".xls", StringComparison.OrdinalIgnoreCase)) { speciesno = "010101"; } //上传文件到服务器目录 postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}&confirm=1"; if (!string.IsNullOrEmpty(idValue)) { string token = ""; string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx"; HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8); Dictionary loginPmsDic = new Dictionary(); loginPmsDic.Add("method", "Login"); loginPmsDic.Add("username", HttpUtility.UrlEncode(ERPInfo.Instance.UserName)); loginPmsDic.Add("password", HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord)); HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult); if (loginResponse != null && !string.IsNullOrEmpty(loginResult)) { JObject jObject = JsonConvert.DeserializeObject(loginResult); if (jObject.ContainsKey("success")) { if ((jObject["success"] + "").Equals("True")) { if (jObject.ContainsKey("token")) { token = jObject["token"] + ""; } } } } if (!string.IsNullOrEmpty(token)) { //string selectSql = $"select * from P_fm_FileTab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{idValue}' and dllcoid = '1000202') and speciesno = '{speciesno}' and sname = '{name.Replace(" ", "")}'"; //DataTable deleteTable = BaseImpl.GetDataTableResult(selectSql); //if (deleteTable != null && deleteTable.Rows.Count > 0) //{ // foreach (DataRow deleteRow in deleteTable.Rows) // { // string field = HttpUtility.UrlEncode(deleteRow["fileId"] + ""); // string webpath = HttpUtility.UrlEncode(deleteRow["webpath"] + ""); // //删除文件 // string deleteUrl = "{0}Api/FileUploadApi.ashx?fileId={1}&filename={2}&method={3}"; // deleteUrl = string.Format(deleteUrl, SystemInfo.Instance.OAUrl, field, webpath, "DoDelete"); // HttpHelper.Setting("application/x-www-form-urlencoded", null, null); // Dictionary deleteHeaderDic = new Dictionary(); // deleteHeaderDic.Add("Authorization", $"Bearer {token}"); // HttpWebResponse deleteWebResponse = HttpHelper.Post(deleteUrl, fileStream, null, deleteHeaderDic, out string deleteResult); // } //} postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, "1000202", HttpUtility.UrlEncode(idValue), "file", fileBytes.Length, 0, HttpUtility.UrlEncode(name), "DoWebUpload", speciesno); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; Dictionary headerDic = new Dictionary(); headerDic.Add("Authorization", $"Bearer {token}"); HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { if (jsonObject.ContainsKey("other")) { fileId = jsonObject["other"] + ""; } isUpload = true; } else { if (jsonObject.ContainsKey("msg")) { returnMsg = jsonObject["msg"] + ""; } isUpload = false; } } else { returnMsg = "上传请求失败"; isUpload = false; } } else { returnMsg = loginResult; isUpload = false; } } else { returnMsg = "上传节点值不能为空"; isUpload = false; } } catch (Exception ex) { returnMsg = ex.Message; throw new Exception($"文件{Path.GetFileName(filePath)}上传失败\r\n{ex.Message}"); isUpload = false; } msg = returnMsg; outFileId = fileId; return isUpload; } private bool UploadFileToAudit(string filePath, string idValue, string speciesno, out string msg, out string outFileId) { bool isUpload = false; string File = filePath; string returnMsg = ""; string fileId = ""; string postUrl = ""; try { //获取文件信息 FileInfo fileInfo = new FileInfo(File); string suffix = Path.GetExtension(File); string name = fileInfo.Name; DateTime creationTime = fileInfo.CreationTime; byte[] fileBytes = ConvertFileToBytes(File); string fileStream = Convert.ToBase64String(fileBytes); string userId = ERPInfo.Instance.UserId; DateTime uploadTime = DateTime.Now; string code = ""; string namepattern = @"^(.*-S[A-Z]\d*)(.*)$"; Match namematch = Regex.Match(Path.GetFileNameWithoutExtension(fileInfo.Name).Trim(), namepattern); if (namematch.Success) { code = namematch.Groups[1].Value; } //上传文件到服务器目录 postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&speciesno={8}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}&confirm=1"; if (!string.IsNullOrEmpty(idValue)) { string token = ""; string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx"; HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8); Dictionary loginPmsDic = new Dictionary(); loginPmsDic.Add("method", "Login"); loginPmsDic.Add("username", HttpUtility.UrlEncode(ERPInfo.Instance.UserName)); loginPmsDic.Add("password", HttpUtility.UrlEncode(ERPInfo.Instance.InPassWord)); HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult); if (loginResponse != null && !string.IsNullOrEmpty(loginResult)) { JObject jObject = JsonConvert.DeserializeObject(loginResult); if (jObject.ContainsKey("success")) { if ((jObject["success"] + "").Equals("True")) { if (jObject.ContainsKey("token")) { token = jObject["token"] + ""; } } } } if (!string.IsNullOrEmpty(token)) { //string selectSql = $"select * from P_fm_FileTab where parentid in (select dirid from P_fm_DirectoryTab where pid = '{idValue}' and dllcoid = '1000202') and speciesno = '{speciesno}' and sname = '{name.Replace(" ", "")}'"; //DataTable deleteTable = BaseImpl.GetDataTableResult(selectSql); //if (deleteTable != null && deleteTable.Rows.Count > 0) //{ // foreach (DataRow deleteRow in deleteTable.Rows) // { // string field = HttpUtility.UrlEncode(deleteRow["fileId"] + ""); // string webpath = HttpUtility.UrlEncode(deleteRow["webpath"] + ""); // //删除文件 // string deleteUrl = "{0}Api/FileUploadApi.ashx?fileId={1}&filename={2}&method={3}"; // deleteUrl = string.Format(deleteUrl, SystemInfo.Instance.OAUrl, field, webpath, "DoDelete"); // HttpHelper.Setting("application/x-www-form-urlencoded", null, null); // Dictionary deleteHeaderDic = new Dictionary(); // deleteHeaderDic.Add("Authorization", $"Bearer {token}"); // HttpWebResponse deleteWebResponse = HttpHelper.Post(deleteUrl, fileStream, null, deleteHeaderDic, out string deleteResult); // } //} postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, "1000202", HttpUtility.UrlEncode(idValue), "file", fileBytes.Length, 0, HttpUtility.UrlEncode(name), "DoWebUpload", speciesno); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; Dictionary headerDic = new Dictionary(); headerDic.Add("Authorization", $"Bearer {token}"); HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { if (jsonObject.ContainsKey("other")) { fileId = jsonObject["other"] + ""; BaseImpl.ExecSqlValue($"update p_fm_filetab set isdisabled = 2 where fileid = '{fileId}'"); } isUpload = true; } else { if (jsonObject.ContainsKey("msg")) { returnMsg = jsonObject["msg"] + ""; } isUpload = false; } } else { returnMsg = "上传请求失败"; isUpload = false; } } else { returnMsg = loginResult; isUpload = false; } } else { returnMsg = "上传节点值不能为空"; isUpload = false; } } catch (Exception ex) { returnMsg = ex.Message; throw new Exception($"文件{Path.GetFileName(filePath)}上传失败\r\n{ex.Message}"); isUpload = false; } msg = returnMsg; outFileId = fileId; return isUpload; } /// /// 记录附件变更数据 /// /// /// public string BuildBomFileTabSql(DataTable dt, string billno) { if (dt == null || dt.Rows.Count == 0) return string.Empty; var sb = new StringBuilder(); sb.AppendLine("BEGIN TRANSACTION;"); foreach (DataRow row in dt.Rows) { int fileId = Convert.ToInt32(row["文件ID"]); string fileName = row["附件名称"].ToString().Replace("'", "''");// 单引号转义 string speciesNo = row["目录ID"].ToString().Replace("'", "''");// → speciesno string dirName = row["目录名称"].ToString().Trim();// → pid int pid = 0; int.TryParse(dirName, out pid); //目录名称若为数字则转换,否则默认为 0 sb.AppendFormat( @"IF NOT EXISTS ( SELECT 1 FROM bom_filetab WHERE fileid = {0} AND speciesno = '{1}' AND pid = {2}) INSERT INTO bom_filetab (billno, fileid, filename, speciesno, pid) VALUES ('{4}',{0}, N'{3}', '{1}', {2}); ", fileId, speciesNo, pid, fileName, billno); } sb.AppendLine("COMMIT TRANSACTION;"); return sb.ToString(); } /// /// 附件转换byte[] /// /// 附件路径 /// 二进制 private byte[] ConvertFileToBytes(string filePath) { byte[] bytContent = null; System.IO.FileStream fs = null; System.IO.BinaryReader br = null; try { fs = new FileStream(filePath, System.IO.FileMode.Open); } catch (Exception) { throw; } finally { if (fs != null) br = new BinaryReader((Stream)fs); if (br != null) bytContent = br.ReadBytes((Int32)fs.Length); if (fs != null) fs.Dispose(); } return bytContent; } /// /// 解析code信息 /// /// /// /// /// /// private void GetFileCodeInfo(string sourceCode, out string code, out string name, out string bb, out int bc) { string namepattern = @"^(.*-S[A-Z]\d*)(.*)$"; string pattern = @"^(.*?)(\d+)?$"; string childcode = ""; string childname = ""; string childsourceCode = ""; string childsourceBB = ""; int childsourceBC = 0; Match namematch = Regex.Match(Path.GetFileNameWithoutExtension(sourceCode).Trim(), namepattern); if (namematch.Success) { childcode = namematch.Groups[1].Value.Trim(); childname = namematch.Groups[2].Value.Trim(); } Match match = Regex.Match(childcode, pattern); if (match.Success) { childsourceCode = match.Groups[1].Value; int.TryParse(match.Groups[2].Value, out childsourceBC);//版次 Match bbMatch = Regex.Match(childsourceCode, @"^.*?([A-Za-z]+)(\d*)$"); if (bbMatch.Success) { childsourceBB = bbMatch.Groups[1].Value.Trim(); } } code = childsourceCode; name = childname; bb = childsourceBB; bc = childsourceBC; } /// /// 解析code信息 /// /// /// /// /// /// private bool GetOtherFileCodeInfo(string fileName, out string code, out string spec, out string name, out string extension, out string bb, out int bc) { string namepattern = @"^(\S+)\s+(\S*-S[A-Z][0-9]*)\s+(.+)(\.[^.]+)$"; string pattern = @"^(.*?)(\d+)?$"; var match = Regex.Match(fileName, namepattern); code = ""; spec = ""; name = ""; extension = ""; bb = ""; bc = 0; if (match.Success) { code = match.Groups[1].Value.Trim(); spec = match.Groups[2].Value.Trim(); name = match.Groups[3].Value.Trim(); extension = match.Groups[4].Value.Trim(); match = Regex.Match(spec, pattern); if (match.Success) { string childsourceCode = match.Groups[1].Value; int.TryParse(match.Groups[2].Value, out bc);//版次 Match bbMatch = Regex.Match(childsourceCode, @"^.*?([A-Za-z]+)(\d*)$"); if (bbMatch.Success) { bb = bbMatch.Groups[1].Value.Trim(); } } return true; } else { return false; } } } }