supplierDownload.aspx.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 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 = "";
  155. if (!string.IsNullOrEmpty(tid) && !string.IsNullOrEmpty(orderSn))
  156. {
  157. rname = formatMemo(dr["seller_memo"]).Replace(orderSn, tid);
  158. rname = rname + "《" + orderSn + "》";
  159. rname = rname + ext;
  160. }
  161. int IsFileEncrypt = IsFileEncrypted(fname);
  162. if (IsFileEncrypt == 1 && File.Exists(fname))
  163. {
  164. string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
  165. var sb = new StringBuilder(key);
  166. //Linux系统的接口要调用一次,Windows系统要调用两次
  167. CreateUserKey(sb, key.Length);
  168. CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
  169. int result = InitAesKey(sb, sb.Length);
  170. result = IsInitedAesKey();
  171. if (result != 1)
  172. {
  173. addLog(ctid, userId, "初始化秘钥失败" + result, 0);
  174. noFileLst.Add("'" + ctid + "'");
  175. continue;
  176. }
  177. uint a = DecFile(fname);
  178. if (a != 0)
  179. {
  180. addLog(ctid, userId, "解密失败" + a, 0);
  181. noFileLst.Add("'" + ctid + "'");
  182. continue;
  183. }
  184. }
  185. if (string.IsNullOrEmpty(fname))
  186. {
  187. noFileLst.Add("'" + ctid + "'");
  188. continue;
  189. }
  190. files.Add(fname);
  191. ctidLst.Add(ctid);
  192. rnameList.Add(rname);
  193. fileMd5 += "," + dr["FileMd5"].ToString();
  194. fileNames += "#$#" + Path.GetFileName(fname);
  195. if (onlyDownFile != 1 && mvClientDown != 1)
  196. {
  197. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, rname);
  198. }
  199. }
  200. if (files.Count == 0)
  201. {
  202. conErc("没有找到相关的设计附件");
  203. return;
  204. }
  205. /*if (noFileLst.Count > 0)
  206. {
  207. string tips = "";
  208. string notids = string.Join(",", noFileLst.ToArray());
  209. sql = new StringBuilder();
  210. 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, "找不到设计文件");
  211. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  212. tips += "找不到文件,单号:" + notids;
  213. conErc(tips);
  214. return;
  215. }*/
  216. if (mvClientDown == 1)
  217. {
  218. for (int i = 0; i < files.Count; i++)
  219. {
  220. if (onlyDownFile != 1)
  221. updateIsDownSuccess(userId, ctidLst[i]);
  222. }
  223. string key = "file_client_down_list_" + userId;
  224. string data = "{\"hexdata\":\"" + tids + "\",\"fileMd5\":\"" + fileMd5.Substring(1) + "\",\"supplier\":\""
  225. + (Request["supplier"] != null ? Request["supplier"].ToString() : "0") + "\",\"fileName\":\"" + System.Web.HttpUtility.UrlEncode(fileNames, System.Text.Encoding.GetEncoding("GB2312")) + "\"}";
  226. erpRedis.RedisHelper.ListLeftPush(key, data);
  227. return;
  228. }
  229. if (ctidLst.Count > 0)
  230. {
  231. ctids = string.Join(",", ctidLst);
  232. if (!string.IsNullOrEmpty(ctids))
  233. {
  234. CeErpTradeCell.ExecuteNonQuery(string.Format("update CE_ErpTradeCell set IsHaveNewOrder = 2 where ctid in ({0}) ;", ("'" + ctids.Replace(",", "','") + "'")));
  235. }
  236. }
  237. if (files.Count == 1)
  238. {
  239. downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient, rnameList[0]);
  240. }
  241. else
  242. {
  243. ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient, rnameList); //downLoadFile(userId, ctidLst[i], files[i]);
  244. }
  245. //conSuc("文件已下载完成");
  246. return;
  247. }
  248. catch (Exception ex)
  249. {
  250. conErc("错误的下载访问" + ex.Message);
  251. XLog.SaveLog(0, "download" + ex.Message);
  252. return;
  253. }
  254. }
  255. private string formatMemo(object memo)
  256. {
  257. string m = memo.ToString();
  258. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  259. return m;
  260. }
  261. Dictionary<string, string> replaceRules = new Dictionary<string, string>
  262. {
  263. { "皙贝", "白卡" },
  264. { "睿狐", "莱尼" },
  265. { "岚蝶", "安格" },
  266. { "琮纹", "刚古" },
  267. { "珠光", "珠光" },
  268. { "溪雪", "珠光" },
  269. { "雅柔", "雅柔" },
  270. { "萱姿", "雅柔" },
  271. { "草香", "草香" },
  272. { "芳怡", "草香" },
  273. { "金绒", "牛皮" },
  274. { "素芸", "棉卡" },
  275. { "玉蕊", "蛋壳" }
  276. };
  277. private void copyFile(string date, string supplier, string file, string rname)
  278. {
  279. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  280. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  281. string fname = Path.GetFileName(file);
  282. foreach (var rule in replaceRules)
  283. {
  284. fname = fname.Replace(rule.Key, rule.Value);
  285. }
  286. File.Copy(file, path + "\\" + fname, true);
  287. if (!File.Exists(path + "\\" + fname))
  288. {
  289. File.Copy(file, path + "\\" + fname, true);
  290. }
  291. }
  292. private string getDesignTime(object v)
  293. {
  294. if (v.ToString() == "") return "";
  295. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  296. }
  297. private string getDesignDate(object v)
  298. {
  299. return DateTime.Now.ToString("yyyy-MM-dd");
  300. /*if (v.ToString() == "") return "";
  301. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  302. }
  303. /// 批量进行多个文件压缩到一个文件
  304. /// </summary>
  305. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  306. /// <param name="zipFileName">生成的zip文件名称</param>
  307. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient, List<string> rnameList)
  308. {
  309. MemoryStream ms = new MemoryStream();
  310. byte[] buffer = null;
  311. List<string> addFiles = new List<string>();
  312. List<string> addCtid = new List<string>();
  313. using (ZipFile file = ZipFile.Create(ms))
  314. {
  315. file.BeginUpdate();
  316. //file.NameTransform = new ZipNameTransform();
  317. file.NameTransform = new MyNameTransfom();
  318. for (int i = 0; i < ctidLst.Count; i++)
  319. {
  320. if (File.Exists(files[i]))
  321. {
  322. try
  323. {
  324. file.Add(files[i]);
  325. addFiles.Add(files[i]);
  326. addCtid.Add(ctidLst[i]);
  327. }
  328. catch (Exception ex)
  329. {
  330. }
  331. }
  332. }
  333. file.CommitUpdate();
  334. buffer = new byte[ms.Length];
  335. ms.Position = 0;
  336. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  337. ms.Flush();
  338. ms.Close();
  339. }
  340. Response.Clear();
  341. Response.Buffer = true;
  342. Response.ContentType = "application/x-zip-compressed";
  343. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  344. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  345. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
  346. Response.AddHeader("Content-Length", buffer.Length.ToString());
  347. Response.BinaryWrite(buffer);
  348. Page.Response.Flush();
  349. //for (int i = 0; i < addFiles.Count; i++)
  350. //{
  351. // updateIsDownSuccess(userId, addCtid[i]);
  352. //}
  353. //sql = new StringBuilder();
  354. //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, "下载设计文件");
  355. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  356. }
  357. //public static object downfileObj = new object();
  358. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient, string fname)
  359. {
  360. string filePath = file;
  361. string dfile = Path.GetFileName(file);
  362. FileStream fs = new FileStream(filePath, FileMode.Open);
  363. byte[] bytes = new byte[(int)fs.Length];
  364. fs.Read(bytes, 0, bytes.Length);
  365. fs.Close();
  366. Response.Clear();
  367. //
  368. Response.ClearContent();
  369. Response.ClearHeaders();
  370. Response.ContentType = "application/octet-stream";
  371. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  372. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  373. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  374. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
  375. Response.AddHeader("Content-Length", bytes.Length.ToString());
  376. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  377. Response.BinaryWrite(bytes);
  378. Response.Flush();
  379. //updateIsDownSuccess(userId, ctid);
  380. //StringBuilder sql = new StringBuilder();
  381. //string tids = string.Join(",", ctid);
  382. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  383. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  384. //sql = new StringBuilder();
  385. //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, "下载设计文件");
  386. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  387. }
  388. public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
  389. {
  390. CeErpTradeLog log = new CeErpTradeLog();
  391. log.tid = ctid;
  392. log.UserId = userid;
  393. log.Con = con;
  394. log.OrderState = orderState;
  395. log.AfterSaleState = aftersaleState;
  396. log.OperateTime = DateTime.Now;
  397. log.Create();
  398. }
  399. }