using BizCom; using ICSharpCode.SharpZipLib.Zip; using Microsoft.Win32; using SevenZip; using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Text; using System.Web; using Utils; using SiteCore; using Aspose.Imaging.ImageOptions; using Aspose.Imaging; using Microsoft.WindowsAPICodePack.Shell; using System.Drawing.Imaging; using CorelDRAW; using System.Security.Principal; using System.Threading.Tasks; using System.Threading; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using System.Data; public partial class uploadFile : System.Web.UI.Page { public static string upPath = ConfigurationManager.AppSettings["upPath"]; public static string curPath = ConfigurationManager.AppSettings["curPath"]; static CdrConvert cdrConvert = new CdrConvert(); private void conSuc(string msg) { Response.Write("{\"res\":\"1\",\"msg\":\"" + msg + "!\"}"); //Response.End(); } private void conErc(string msg) { Response.Write("{\"res\":\"0\",\"msg\":\"" + msg + "!\"}"); //Response.End(); } public string GetMD5HashFromFile(HttpPostedFile file) { try { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file.InputStream); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { XLog.SaveLog(0, "上传MD5错误!" + ex.Message); } return ""; } private static byte[] GetBlobByHttpPostedFile(HttpPostedFile httpPostedFile) { var contentLength = httpPostedFile.ContentLength; var result = new byte[contentLength]; var inputStream = httpPostedFile.InputStream; inputStream.Read(result, 0, contentLength); return result; } protected void Page_Load(object sender, EventArgs e) { //if (CurrentUser == null) //{ // Response.Write(err); // return; //} //CeErpTradeCell.GetByCtid("1717009344450030601"); if (Request.Files.Count < 1) { conErc("空文件!"); return; } int userId = 0; int orgid = 0; if (Request["userid"] != null) { userId = Convert.ToInt32(Request["userid"]); } if (Request["orgid"] != null) { orgid = Convert.ToInt32(Request["orgid"]); } HttpPostedFile postFile = Request.Files[0]; if (postFile != null) { string file_name = postFile.FileName; string namePattern = @"《(.*?)》"; Regex nameReg = new Regex(namePattern, RegexOptions.IgnoreCase | RegexOptions.Multiline, TimeSpan.FromSeconds(2));//2秒后超时 MatchCollection nameMatches = nameReg.Matches(file_name);//设定要查找的字符串 if (nameMatches.Count > 0) { foreach (Match match in nameMatches) { file_name = file_name.Replace(match.Value, ""); } } file_name = file_name.Replace("(", "("); file_name = file_name.Replace(")", ")"); string ctid = MidStrEx(file_name, "(", ")").Trim(); if (string.IsNullOrEmpty(ctid)) { conErc("上传的文件名格式不正确"); return; } string memoCtid = ctid; if (ctid.IndexOf("C") == -1) { if (file_name.IndexOf("[") != -1 && file_name.IndexOf("C") != -1) { if (ctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1] 对应ctid是 S_S_C1_1962772776865084101 { int lastIndex = ctid.LastIndexOf("S_"); //最后一个S_的位置 string sPre = ctid.Substring(0, lastIndex + 2); //S_S_ string initTid = ctid.Substring(lastIndex + 2, ctid.Length - lastIndex - 2); //1962772776865084101 string pre_ctid = MidStrEx(file_name, "[", "]"); //C1 if (pre_ctid.IndexOf("+") != -1) { pre_ctid = "C" + pre_ctid.Split('+')[1]; } memoCtid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101 } else { string pre_ctid = MidStrEx(file_name, "[", "]"); if (pre_ctid.IndexOf("+") != -1) { pre_ctid = "C" + pre_ctid.Split('+')[1]; } memoCtid = pre_ctid + "_" + ctid; } } } CeErpTradeCell entity = null; if (ctid != "") entity = CeErpTradeCell.GetByCode(ctid); if (entity == null) entity = CeErpTradeCell.GetByCtid(ctid); if (entity == null) entity = CeErpTradeCell.GetByCtid(memoCtid); try { if (entity != null) { string pname = Path.GetFileNameWithoutExtension(file_name); if (entity.IsRefund == 2) { StringBuilder sql = new StringBuilder(); sql.AppendFormat("select refund_status from CE_ErpTradeOrder where tid='{0}'", entity.tid); DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0]; bool isAll = true; foreach (DataRow dr in dt.Rows) { if ("NO_REFUND".Equals(dr["refund_status"])) { isAll = false; break; } } if (isAll) { conErc("此单退款,不允许上传"); return; } } if (entity.seller_memo != pname) { conErc("上传的文件名与备注不符合!"); return; } if (entity.OrderState == -1) { conErc("还未审核不允许上传"); return; } if (entity.OrderState < (int)OrderState.设计中 && orgid != 10 && orgid != 4) { conErc("还未开始设计不允许上传"); return; } //if (pname.IndexOf("现货") != -1) //{ // conErc("设计款的单文件名不能有现货字眼"); // return; //} //更新状态 if (entity.OrderState >= (int)OrderState.下单完成) { conErc("已经下单无法上传!"); return; } if (entity.IsVerifyToSupplier) { conErc("订单已到车间无法上传!"); return; } string extend = Path.GetExtension(file_name).ToLower(); if (!(extend == ".cdr" || extend == ".zip" || extend == ".rar" || extend == ".pdf")) { conErc("只允许上传zip和cdr文件!"); return; } if (entity.OrderState != 5) { entity.FinishDesignTime = DateTime.Now; if (entity.isDianziOrder == 1 || entity.ProductId == 57 || entity.ProductId == 28) { entity.OrderState = 6; entity.SupplierId = 35; entity.FinishPlaceTime = DateTime.Now; bool sendResult = commonHelper.SetOrderDummyDelivery(entity.tid); if (sendResult) { entity.OrderState = 7; } } else entity.OrderState = 5; //设计完成 //if (entity.IsReturn == 2) //2是下单人打回给设计的,重新上传的话,需要清除打回 //{ entity.IsXianHuo = 0; entity.IsVerifyToSupplier = false; //} } entity.IsReturn = 0; if (entity.MemoOpt == 1 || entity.MemoOpt == 2) { entity.MemoOpt = 0; } if (entity.payment < 500) { if (entity.seller_memo.Contains("插卡") && entity.ProductCount != null && !entity.seller_memo.Contains("S_")) { int num = 0; try { string text = entity.ProductCount; string pattern = @"(\d+)\s*张"; MatchCollection matches = Regex.Matches(text, pattern); foreach (Match match in matches) { if (match.Success) { num = Convert.ToInt32(match.Groups[1].Value); break; } } } catch (Exception ex) { } if (num >= 100) { entity.IsVerifyToSupplier = true; entity.SupplierId = 3; entity.FinishPlaceTime = DateTime.Now; } } if ((((entity.seller_memo.Contains("条幅彩色") && !entity.seller_memo.Contains("辽宁") && !entity.seller_memo.Contains("山东")) || entity.seller_memo.Contains("贡锻布") || entity.seller_memo.Contains("贡缎布") || entity.seller_memo.Contains("旗帜布")) && !entity.seller_memo.Contains("双喷")) || entity.seller_memo.Contains("帆布")) { entity.IsVerifyToSupplier = true; entity.SupplierId = 98; entity.FinishPlaceTime = DateTime.Now; } } if(entity.ProductId == 2690) { entity.IsVerifyToSupplier = true; entity.SupplierId = 97; entity.FinishPlaceTime = DateTime.Now; } string dPath = entity.FinishDesignTime.GetValueOrDefault().ToString("yyyyMMdd"); //XLog.SaveLog(5, dPath); string sPath = Path.Combine(upPath, dPath); string cpath = Path.Combine(upPath, entity.FinishDesignTime.GetValueOrDefault().ToString("yyyyMM")); //XLog.SaveLog(5, sPath); //XLog.SaveLog(5, Directory.Exists(sPath).ToString()); if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath); if (!Directory.Exists(cpath)) Directory.CreateDirectory(cpath); string saveFile = Path.Combine(sPath, file_name); string f_ext = Path.GetExtension(saveFile); string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" }; string _file = ""; foreach (string ext in extArr) { if (f_ext != ext) { _file = saveFile.Replace(f_ext, ext); if (File.Exists(_file)) File.Delete(_file); } else { if (File.Exists(saveFile)) File.Delete(saveFile); } } //上传文件 postFile.SaveAs(saveFile); entity.FileMd5 = GetMD5HashFromFile(postFile); //XLog.SaveLog(0, saveFile); entity.UpdateTime = DateTime.Now; entity.Update(); //CeErpTradeCell.UpdateRelationOrder(entity); CeErpTradeCell.UpdateRelationOrder(entity.ctid); CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, userId, "上传设计文件-" + saveFile); if (ctid.IndexOf("S_") >= -1) { StringBuilder sql = new StringBuilder(); sql.AppendFormat("select * from Ce_ErpTradeCellExtend where ctid='{0}'", entity.ctid); DataTable cellEx = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0]; if (cellEx.Rows.Count > 0) { string txtReprintTime = cellEx.Rows[0]["ReprintTime"].ToString(); if (!string.IsNullOrEmpty(txtReprintTime) && !"null".Equals(txtReprintTime)) { DateTime reprint = DateTime.Parse(txtReprintTime); if (DateTime.Compare(DateTime.Now.AddHours(-24), reprint) >= 0) { string parentId = entity.ctid.Substring(2); string update_sql = string.Format("update Ce_ErpTradeAfterSaleExtend set ReprintOut = ReprintOut+1 where tid= '{0}' ;", parentId); CeErpTradeLog.ExecuteNonQuery(update_sql); } } } } if (Path.GetExtension(saveFile).IndexOf("cdr", StringComparison.OrdinalIgnoreCase) != -1) { //string sql = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", saveFile); //CeErpTradeLog.ExecuteNonQuery(sql); } else if (Path.GetExtension(saveFile).IndexOf("zip", StringComparison.OrdinalIgnoreCase) != -1 || Path.GetExtension(saveFile).IndexOf("rar", StringComparison.OrdinalIgnoreCase) != -1) { try { DecompressZIPandRAR(saveFile, sPath, file_name); } catch (Exception ex) { CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, entity.DesignUserId, "解压失败!"); XLog.SaveLog(0, "上传解压发生错误!" + ex.Message); } //Decompress(saveFile,sPath); } //new Thread(new ThreadStart(delegate () //{ //System.Threading.Thread.Sleep(2000); if (Path.GetExtension(saveFile).IndexOf("cdr", StringComparison.OrdinalIgnoreCase) != -1) { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); writeLog("上传完成!" + saveFile); Task.Run(async () => { string filePath = Path.GetFullPath(saveFile); string targPath = Path.Combine(cpath, file_name); using (identity.Impersonate()) { try { if (File.Exists(filePath)) { cdrConvert.CdrConvertPng(filePath, targPath); } } catch (Exception ex) { XLog.SaveLog(0, filePath + ",转成图片出错:" + ex.Message); } } }); } //})).Start(); conSuc("上传成功!"); return; } else { conErc("找不到对应的订单"); return; } } catch (Exception ex) { conErc("上传发生错误!" + CommonHelper.FormatTextArea(ex.Message)); CeErpTradeLog.AddLog(entity.ctid, entity.OrderState, entity.DesignUserId, "上传失败!"); XLog.SaveLog(0, "上传发生错误!" + ex.Message); return; } finally { if (postFile != null) { postFile.InputStream.Close(); } } } conErc("空文件!"); } class CdrConvert { private object lockObject = new object(); public void CdrConvertPng(string filePath, string targPath) { lock (lockObject) { writeLog("开始截图!" + filePath); targPath = targPath.Replace(".cdr", ".png"); try { Application cdr = new Application(); cdr.OpenDocument(filePath, 1); cdr.ActiveDocument.ExportBitmap( targPath, cdrFilter.cdrPNG, cdrExportRange.cdrCurrentPage, cdrImageType.cdrRGBColorImage, 0, 0, 72, 72, cdrAntiAliasingType.cdrNoAntiAliasing, false, true, true, false, cdrCompressionType.cdrCompressionNone, null).Finish(); cdr.ActiveDocument.Close(); cdr.Quit(); cdr = null; } catch (Exception ex) { XLog.SaveLog(0, targPath + ",转成图片出错:" + ex.Message); } finally { KillProcessByName("CorelDRW"); } } } void KillProcessByName(string processName) { Process[] processes = Process.GetProcessesByName(processName); foreach (Process process in processes) { try { process.Kill(); process.WaitForExit(); // 等待进程退出 } catch (Exception ex) { } } } } private void DecompressZIPandRAR(string zipFile, string targetPath, string filename) { string notExtension = filename.Substring(0, filename.Length - 4); SevenZipExtractor.SetLibraryPath(Server.MapPath("bin\\7z.dll")); LibraryFeature lf = SevenZipExtractor.CurrentLibraryFeatures; using (SevenZipExtractor szExtra = new SevenZipExtractor(zipFile)) { //szExtra.ExtractArchive("d:\\temp"); foreach (string afn in szExtra.ArchiveFileNames) { if (afn.IndexOf(notExtension, StringComparison.OrdinalIgnoreCase) != -1) { szExtra.ExtractFiles(targetPath, afn); break; } } } } private void Decompress(string GzipFile, string targetPath) { //string directoryName = Path.GetDirectoryName(targetPath + "\\") + "\\"; string directoryName = targetPath + "\\"; if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录 //helper.writeLog(GzipFile); //helper.writeLog(directoryName); string CurrentDirectory = directoryName; byte[] data = new byte[2048]; int size = 2048; ZipEntry theEntry = null; Stream _stream = File.OpenRead(GzipFile); if (_stream.Length == 0) { _stream.Close(); return; } try { using (ZipInputStream s = new ZipInputStream(_stream)) { while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.IsDirectory) {// 该结点是目录 if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name); } else { if (theEntry.Name != String.Empty && (theEntry.Name.IndexOf(".png", StringComparison.OrdinalIgnoreCase) != -1 || theEntry.Name.IndexOf(".jpg", StringComparison.OrdinalIgnoreCase) != -1)) { //解压文件到指定的目录 using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name)) { while (true) { size = s.Read(data, 0, data.Length); if (size <= 0) break; streamWriter.Write(data, 0, size); } streamWriter.Close(); } break; } } } s.Close(); } } catch (Exception ex) { XLog.SaveLog(0, "解压uncau:" + ex.Message); } } public string unCompressRAR(string unRarPatch, string rarPatch, string rarName) { string the_rar; RegistryKey the_Reg; object the_Obj; string the_Info; try { the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); if (Directory.Exists(unRarPatch) == false) { Directory.CreateDirectory(unRarPatch); } the_Info = "x " + rarName + " " + unRarPatch + " -y"; ProcessStartInfo the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; the_StartInfo.WorkingDirectory = rarPatch;//获取压缩包路径 Process the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); the_Process.WaitForExit(); the_Process.Close(); } catch (Exception ex) { throw ex; } return unRarPatch; } private void ShellCdrConvertPng(string path, string targPath) { ShellFile shellFile = ShellFile.FromFilePath(path); System.Drawing.Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap; //在画板的指定位置画图 targPath = targPath.Replace(".cdr", ".png"); shellThumb.Save(targPath, ImageFormat.Png); shellThumb.Dispose(); shellFile.Dispose(); } private void CdrConvertPng(string path, string targPath) { using (Aspose.Imaging.FileFormats.Cdr.CdrImage image = (Aspose.Imaging.FileFormats.Cdr.CdrImage)Aspose.Imaging.Image.Load(path)) { PngOptions options = new Aspose.Imaging.ImageOptions.PngOptions(); options.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha; // Set rasterization options for fileformat options.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions) image.GetDefaultOptions(new object[] { Aspose.Imaging.Color.White, image.Width, image.Height }); options.VectorRasterizationOptions.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; options.VectorRasterizationOptions.SmoothingMode = Aspose.Imaging.SmoothingMode.None; targPath = targPath.Replace(".cdr", ".png"); image.Save(targPath, options); options.Dispose(); } } private string CdrExPng(string path, string targPath) { try { targPath = targPath.Replace(".cdr", ".png"); Application cdr = new Application(); cdr.OpenDocument(path, 1); cdr.ActiveDocument.ExportBitmap( targPath, cdrFilter.cdrPNG, cdrExportRange.cdrCurrentPage, cdrImageType.cdrRGBColorImage, 0, 0, 72, 72, cdrAntiAliasingType.cdrNoAntiAliasing, false, true, true, false, cdrCompressionType.cdrCompressionNone, null).Finish(); cdr.ActiveDocument.Close(); cdr.Quit(); cdr = null; GC.Collect(); } catch (Exception ex) { XLog.SaveLog(0, path + ",转成图片出错:" + ex.Message); } finally { } return "111"; } private static object cdrpngobj = new object(); private void CdrExportPng(string path, string cdrFile) { lock (cdrpngobj) { string fname = curPath + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png"; string new_fname = path + "\\" + Path.GetFileNameWithoutExtension(cdrFile) + ".png"; CorelDRAW.Application cdr = new CorelDRAW.Application(); cdr.OpenDocument(cdrFile, 1); cdr.ActiveDocument.ExportBitmap( fname, CorelDRAW.cdrFilter.cdrPNG, CorelDRAW.cdrExportRange.cdrCurrentPage, CorelDRAW.cdrImageType.cdrRGBColorImage, 0, 0, 72, 72, CorelDRAW.cdrAntiAliasingType.cdrNoAntiAliasing, false, true, true, false, CorelDRAW.cdrCompressionType.cdrCompressionNone, null).Finish(); cdr.ActiveDocument.Close(); cdr.Quit(); if (File.Exists(fname)) { File.Copy(fname, new_fname); File.Delete(fname); } } } public static string MidStrEx(string sourse, string startstr, string endstr) { string result = string.Empty; int startindex, endindex; try { startindex = sourse.IndexOf(startstr); if (startindex == -1) return result; string tmpstr = sourse.Substring(startindex + startstr.Length); endindex = tmpstr.IndexOf(endstr); if (endindex == -1) return result; result = tmpstr.Remove(endindex); } catch (Exception ex) { Console.WriteLine("MidStrEx Err:" + ex.Message); } return result; } private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log"; private static object logFlag = new object(); public static void writeLog(string log) { lock (logFlag) { using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default)) { sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n"); sw.Flush(); } } } } }