supplierDownload.aspx.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. using BizCom;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using NPOI.OpenXmlFormats.Dml.Diagram;
  4. using NPOI.OpenXmlFormats.Shared;
  5. using SiteCore.Handler;
  6. using SiteCore.Redis;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Configuration;
  10. using System.Data;
  11. using System.Data.SqlClient;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Runtime.InteropServices;
  16. using System.Text;
  17. using System.Web;
  18. using System.Web.Services.Description;
  19. using System.Web.UI;
  20. public partial class supplierDownload : System.Web.UI.Page
  21. {
  22. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  23. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  24. public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
  25. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  26. public static extern uint DecFile(string filename);
  27. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  28. public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
  29. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  30. public static extern void CreateUserKey(StringBuilder key, int len);
  31. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  32. public static extern int InitAesKey(StringBuilder key, int len);
  33. [DllImport("DrvInterface64.dll")]
  34. public static extern int IsInitedAesKey();
  35. private void conErc(string msg)
  36. {
  37. XLog.SaveLog(0, msg);
  38. Response.Write(msg);
  39. //Response.StatusCode = (int)HttpStatusCode.NotFound;
  40. //Response.End();
  41. }
  42. private void conSuc(string msg)
  43. {
  44. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  45. //Response.End();
  46. }
  47. protected void Page_Load(object sender, EventArgs e)
  48. {
  49. if (!IsPostBack)
  50. {
  51. Response.Buffer = true;
  52. downloadMore();
  53. }
  54. }
  55. private string getCanDownFile(string fileName)
  56. {
  57. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  58. foreach (string ext in extArr)
  59. {
  60. string fname = fileName + ext;
  61. if (File.Exists(fname))
  62. {
  63. return ext;
  64. }
  65. }
  66. return "";
  67. }
  68. private void updateIsDownSuccess(int userId, string ctid)
  69. {
  70. try
  71. {
  72. SqlParameter[] sqlParameter ={
  73. new SqlParameter("@mainctids", SqlDbType.VarChar,500),
  74. new SqlParameter("@userid", SqlDbType.VarChar,4),
  75. new SqlParameter("@res", SqlDbType.VarChar, 4000)
  76. };
  77. sqlParameter[0].Value = ctid;
  78. sqlParameter[1].Value = userId;
  79. sqlParameter[2].Direction = ParameterDirection.Output;
  80. CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
  81. CeErpTradeCell.UpdateRelationOrder(ctid);
  82. }
  83. catch (Exception ex)
  84. {
  85. //errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  86. XLog.SaveLog(0, "下载发生错误,ctid:" + ctid + "," + ex.Message);
  87. }
  88. }
  89. private void downloadMore()
  90. {
  91. if (Request["hexdata"] == null || Request["hexdata"].Trim() == "")
  92. {
  93. conErc("错误的下载访问");
  94. return;
  95. }
  96. string tids = Request["hexdata"];
  97. int onlyDownFile = 0;//只下文件
  98. if (Request["onlyfile"] != null)
  99. {
  100. Int32.TryParse(Request["onlyfile"], out onlyDownFile);
  101. }
  102. int userId = 0;
  103. if (Request["userid"] != null)
  104. {
  105. Int32.TryParse(Request["userid"], out userId);
  106. }
  107. int mvClientDown = 0;//转移到客户端下载
  108. string ctids = "";
  109. int isFromClient = 0;
  110. if (onlyDownFile != 1)
  111. {
  112. if (Request["supplier"] == null || Request["supplier"].ToString() != "1")//如果不是只下文件,那他就要是供应商
  113. {
  114. conErc("错误的下载访问");
  115. return;
  116. }
  117. else
  118. {
  119. /* Int32.TryParse(Request["isFromClient"], out isFromClient);
  120. if (userId > 0 && isFromClient != 1)
  121. {
  122. string file_client_down_flg = erpRedis.RedisHelper.StringGet("file_client_down_flg_" + userId);
  123. if (file_client_down_flg != null && file_client_down_flg == "1")
  124. {
  125. mvClientDown = 1;
  126. }
  127. }*/
  128. }
  129. }
  130. try
  131. {
  132. StringBuilder sql = new StringBuilder();
  133. sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5,OrderSn,tid,SupplierId from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1 || isFromClient == 1) ? "" : " and OrderState=5 "));
  134. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  135. if (dt == null || dt.Rows.Count < 1)
  136. {
  137. conErc("没有找到相关订单");
  138. return;
  139. }
  140. string fileMd5 = "", fileNames = "";
  141. List<string> files = new List<string>();
  142. List<string> noFileLst = new List<string>();
  143. List<string> ctidLst = new List<string>();
  144. List<string> rnameList = new List<string>();
  145. foreach (DataRow dr in dt.Rows)
  146. {
  147. string finishDesignTime = getDesignTime(dr["FinishDesignTime"]);
  148. string ctid = dr["ctid"].ToString();
  149. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
  150. string ext = getCanDownFile(df_name);
  151. string fname = df_name + ext;
  152. string tid = dr["tid"].ToString();
  153. string orderSn = dr["OrderSn"].ToString();
  154. string rname = formatMemo(dr["seller_memo"]) + ext;
  155. if ("14".Equals(dr["SupplierId"].ToString()))
  156. {
  157. rname = dealMemoName(rname);
  158. }
  159. int IsFileEncrypt = IsFileEncrypted(fname);
  160. if (IsFileEncrypt == 1 && File.Exists(fname))
  161. {
  162. string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
  163. var sb = new StringBuilder(key);
  164. //Linux系统的接口要调用一次,Windows系统要调用两次
  165. CreateUserKey(sb, key.Length);
  166. CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
  167. int result = InitAesKey(sb, sb.Length);
  168. result = IsInitedAesKey();
  169. if (result != 1)
  170. {
  171. addLog(ctid, userId, "初始化秘钥失败" + result, 0);
  172. noFileLst.Add("'" + ctid + "'");
  173. continue;
  174. }
  175. uint a = DecFile(fname);
  176. if (a != 0)
  177. {
  178. addLog(ctid, userId, "解密失败" + a, 0);
  179. noFileLst.Add("'" + ctid + "'");
  180. continue;
  181. }
  182. }
  183. if (string.IsNullOrEmpty(fname))
  184. {
  185. noFileLst.Add("'" + ctid + "'");
  186. continue;
  187. }
  188. files.Add(fname);
  189. ctidLst.Add(ctid);
  190. rnameList.Add(rname);
  191. fileMd5 += "," + dr["FileMd5"].ToString();
  192. fileNames += "#$#" + Path.GetFileName(fname);
  193. if (onlyDownFile != 1 && mvClientDown != 1)
  194. {
  195. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, rname);
  196. }
  197. }
  198. if (files.Count == 0)
  199. {
  200. conErc("没有找到相关的设计附件");
  201. return;
  202. }
  203. /*if (noFileLst.Count > 0)
  204. {
  205. string tips = "";
  206. string notids = string.Join(",", noFileLst.ToArray());
  207. sql = new StringBuilder();
  208. sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", notids, (int)OrderState.下单完成, 0, "找不到设计文件");
  209. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  210. tips += "找不到文件,单号:" + notids;
  211. conErc(tips);
  212. return;
  213. }*/
  214. if (mvClientDown == 1)
  215. {
  216. for (int i = 0; i < files.Count; i++)
  217. {
  218. if (onlyDownFile != 1)
  219. updateIsDownSuccess(userId, ctidLst[i]);
  220. }
  221. string key = "file_client_down_list_" + userId;
  222. string data = "{\"hexdata\":\"" + tids + "\",\"fileMd5\":\"" + fileMd5.Substring(1) + "\",\"supplier\":\""
  223. + (Request["supplier"] != null ? Request["supplier"].ToString() : "0") + "\",\"fileName\":\"" + System.Web.HttpUtility.UrlEncode(fileNames, System.Text.Encoding.GetEncoding("GB2312")) + "\"}";
  224. erpRedis.RedisHelper.ListLeftPush(key, data);
  225. return;
  226. }
  227. if (ctidLst.Count > 0)
  228. {
  229. ctids = string.Join(",", ctidLst);
  230. if (!string.IsNullOrEmpty(ctids))
  231. {
  232. CeErpTradeCell.ExecuteNonQuery(string.Format("update CE_ErpTradeCell set IsHaveNewOrder = 2 where ctid in ({0}) ;", ("'" + ctids.Replace(",", "','") + "'")));
  233. }
  234. }
  235. if (files.Count == 1)
  236. {
  237. downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient, rnameList[0]);
  238. }
  239. else
  240. {
  241. ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient, rnameList); //downLoadFile(userId, ctidLst[i], files[i]);
  242. }
  243. //conSuc("文件已下载完成");
  244. return;
  245. }
  246. catch (Exception ex)
  247. {
  248. conErc("错误的下载访问" + ex.Message);
  249. XLog.SaveLog(0, "download" + ex.Message);
  250. return;
  251. }
  252. }
  253. private string dealMemoName(string name)
  254. {
  255. string[] al = name.Split('-');
  256. List<string> list = new List<string>();
  257. string pa = string.Empty;
  258. for (int i = 0; i < al.Length; i++)
  259. {
  260. if (i == 1)
  261. {
  262. if (al[i].Contains("(") || al[i].Contains("("))
  263. {
  264. string tname = al[i].Replace(")", "").Replace(")", "").Replace("(", "").Replace("(", "");
  265. if (!string.IsNullOrEmpty(tname))
  266. {
  267. pa = al[i];
  268. }
  269. continue;
  270. }
  271. }
  272. list.Add(al[i]);
  273. }
  274. if (!string.IsNullOrEmpty(pa))
  275. {
  276. list.Insert(3, pa);
  277. }
  278. name = string.Join("-", list);
  279. return name;
  280. }
  281. private string formatMemo(object memo)
  282. {
  283. string m = memo.ToString();
  284. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  285. return m;
  286. }
  287. Dictionary<string, string> replaceRules = new Dictionary<string, string>
  288. {
  289. { "皙贝", "白卡" },
  290. { "睿狐", "莱尼" },
  291. { "岚蝶", "安格" },
  292. { "琮纹", "刚古" },
  293. { "珠光", "珠光" },
  294. { "溪雪", "珠光" },
  295. { "雅柔", "雅柔" },
  296. { "萱姿", "雅柔" },
  297. { "草香", "草香" },
  298. { "芳怡", "草香" },
  299. { "金绒", "牛皮" },
  300. { "素芸", "棉卡" },
  301. { "玉蕊", "蛋壳" }
  302. };
  303. private void copyFile(string date, string supplier, string file, string rname)
  304. {
  305. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  306. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  307. string fname = Path.GetFileName(file);
  308. foreach (var rule in replaceRules)
  309. {
  310. fname = fname.Replace(rule.Key, rule.Value);
  311. }
  312. File.Copy(file, path + "\\" + fname, true);
  313. if (!File.Exists(path + "\\" + fname))
  314. {
  315. File.Copy(file, path + "\\" + fname, true);
  316. }
  317. }
  318. private string getDesignTime(object v)
  319. {
  320. if (v.ToString() == "") return "";
  321. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  322. }
  323. private string getDesignDate(object v)
  324. {
  325. return DateTime.Now.ToString("yyyy-MM-dd");
  326. /*if (v.ToString() == "") return "";
  327. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  328. }
  329. /// 批量进行多个文件压缩到一个文件
  330. /// </summary>
  331. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  332. /// <param name="zipFileName">生成的zip文件名称</param>
  333. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient, List<string> rnameList)
  334. {
  335. MemoryStream ms = new MemoryStream();
  336. byte[] buffer = null;
  337. List<string> addFiles = new List<string>();
  338. List<string> addCtid = new List<string>();
  339. using (ZipFile file = ZipFile.Create(ms))
  340. {
  341. file.BeginUpdate();
  342. //file.NameTransform = new ZipNameTransform();
  343. file.NameTransform = new MyNameTransfom();
  344. for (int i = 0; i < ctidLst.Count; i++)
  345. {
  346. if (File.Exists(files[i]))
  347. {
  348. try
  349. {
  350. file.Add(files[i], rnameList[i]);
  351. addFiles.Add(files[i]);
  352. addCtid.Add(ctidLst[i]);
  353. }
  354. catch (Exception ex)
  355. {
  356. XLog.SaveLog(0, "supplierdownload_ZipFileDownload:" + ex.Message);
  357. }
  358. }
  359. }
  360. file.CommitUpdate();
  361. buffer = new byte[ms.Length];
  362. ms.Position = 0;
  363. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  364. ms.Flush();
  365. ms.Close();
  366. }
  367. Response.Clear();
  368. Response.Buffer = true;
  369. Response.ContentType = "application/x-zip-compressed";
  370. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  371. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  372. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
  373. Response.AddHeader("Content-Length", buffer.Length.ToString());
  374. Response.BinaryWrite(buffer);
  375. Page.Response.Flush();
  376. //for (int i = 0; i < addFiles.Count; i++)
  377. //{
  378. // updateIsDownSuccess(userId, addCtid[i]);
  379. //}
  380. //sql = new StringBuilder();
  381. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
  382. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  383. }
  384. //public static object downfileObj = new object();
  385. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient, string fname)
  386. {
  387. string filePath = file;
  388. string dfile = Path.GetFileName(file);
  389. FileStream fs = new FileStream(filePath, FileMode.Open);
  390. byte[] bytes = new byte[(int)fs.Length];
  391. fs.Read(bytes, 0, bytes.Length);
  392. fs.Close();
  393. Response.Clear();
  394. //
  395. Response.ClearContent();
  396. Response.ClearHeaders();
  397. Response.ContentType = "application/octet-stream";
  398. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  399. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  400. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  401. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.UTF8));
  402. Response.AddHeader("Content-Length", bytes.Length.ToString());
  403. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  404. Response.BinaryWrite(bytes);
  405. Response.Flush();
  406. //updateIsDownSuccess(userId, ctid);
  407. //StringBuilder sql = new StringBuilder();
  408. //string tids = string.Join(",", ctid);
  409. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  410. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  411. //sql = new StringBuilder();
  412. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
  413. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  414. }
  415. public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
  416. {
  417. CeErpTradeLog log = new CeErpTradeLog();
  418. log.tid = ctid;
  419. log.UserId = userid;
  420. log.Con = con;
  421. log.OrderState = orderState;
  422. log.AfterSaleState = aftersaleState;
  423. log.OperateTime = DateTime.Now;
  424. log.Create();
  425. }
  426. }