copydownload.aspx.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. using BizCom;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using SQLData;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Configuration;
  7. using System.Data;
  8. using System.Data.SqlClient;
  9. using System.IO;
  10. using System.Text;
  11. using System.Web;
  12. using System.Web.UI;
  13. using System.Web.UI.WebControls;
  14. public partial class copydownload : System.Web.UI.Page
  15. {
  16. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  17. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  18. private void conErc(string msg)
  19. {
  20. Response.Write("{\"type\":\"error\",\"result\":\"" + msg + "\"}");
  21. //Response.End();
  22. }
  23. private void conSuc(string msg)
  24. {
  25. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  26. //Response.End();
  27. }
  28. protected void Page_Load(object sender, EventArgs e)
  29. {
  30. if (Request["hexdata"] != null)
  31. {
  32. string tids = Request["hexdata"];
  33. if (tids.Trim() == "")
  34. {
  35. conErc("无法下载");
  36. return;
  37. }
  38. int userId = 0;
  39. if (Request["userid"] != null)
  40. {
  41. userId = Convert.ToInt32(Request["userid"]);
  42. }
  43. try
  44. {
  45. string[] tArr = tids.Split(',');
  46. List<string> tLst = new List<string>();
  47. foreach (string id in tArr)
  48. {
  49. tLst.Add("'" + id + "'");
  50. }
  51. tids = string.Join(",", tLst.ToArray());
  52. StringBuilder sql = new StringBuilder();
  53. sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,OrderSn,tid from view_erptradecell where orderstate=5 and ctid in ({0})", tids);
  54. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  55. if (dt == null || dt.Rows.Count < 1)
  56. {
  57. conErc("没有找到相关订单");
  58. return;
  59. }
  60. List<string> files = new List<string>();
  61. string dTime = "";
  62. string fname = "";
  63. int fc = 0;
  64. bool hasFile = false;
  65. string df_name = "";
  66. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  67. List<string> noFileLst = new List<string>();
  68. List<string> errorFileLst = new List<string>();
  69. foreach (DataRow dr in dt.Rows)
  70. {
  71. if (dr["FinishDesignTime"].ToString() == "") continue;
  72. hasFile = false;
  73. DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
  74. DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
  75. if (ftime.CompareTo(splitTime) > 0)
  76. {
  77. dTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
  78. }
  79. else
  80. {
  81. dTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
  82. }
  83. string tid = dr["tid"].ToString();
  84. string orderSn = dr["OrderSn"].ToString();
  85. string rname = "";
  86. df_name = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]);
  87. foreach (string ext in extArr)
  88. {
  89. if (!string.IsNullOrEmpty(tid) && !string.IsNullOrEmpty(orderSn))
  90. {
  91. rname = formatMemo(dr["seller_memo"]).Replace(orderSn, tid);
  92. rname = rname + "《" + orderSn + "》";
  93. }
  94. fname = df_name + ext;
  95. rname = rname + ext;
  96. if (!hasFile)
  97. {
  98. if (File.Exists(fname))
  99. {
  100. bool isCopyError = false;
  101. double payment = 0;
  102. string ctid = dr["ctid"].ToString();
  103. CeErpTradeCell entity = CeErpTradeCell.GetByCtid(ctid);
  104. try
  105. {
  106. if (entity != null)
  107. {
  108. payment = entity.payment;
  109. }
  110. hasFile = true;
  111. files.Add(fname);
  112. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname, payment, rname);
  113. fc++;
  114. }
  115. catch (Exception ex)
  116. {
  117. isCopyError = true;
  118. errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  119. XLog.SaveLog(0, "复制文件发生错误," + fname + "," + ex.Message);
  120. }
  121. //复制完成后修改数据
  122. if (!isCopyError)
  123. {
  124. try
  125. {
  126. if (entity != null)
  127. {
  128. //update ce_erptradecell WITH(ROWLOCK) set FinishPlaceTime = getdate(), OrderState = 6, IsReturn = 0, PlaceUserId = @userid where CHARINDEX(',' + ctid + ',',',' + @mainctids + ',')> 0 and orderstate = 5 and isDianziOrder = 0
  129. //insert into CE_ErpTradeLog(tid, orderstate, userid, operatetime, con) select ctid,6,@userid,getdate(),'下载设计文件' from ce_erptradecell where CHARINDEX(',' + ctid + ',', ',' + @mainctids + ',') > 0
  130. entity.FinishPlaceTime = DateTime.Now;
  131. entity.OrderState = 6;
  132. entity.IsReturn = 0;
  133. entity.PlaceUserId = userId;
  134. entity.Update();
  135. CeErpTradeLog logenty = new CeErpTradeLog();
  136. logenty.tid = ctid;
  137. logenty.OrderState = 6;
  138. logenty.UserId = userId;
  139. logenty.OperateTime = DateTime.Now;
  140. logenty.Con = "下载设计文件";
  141. logenty.Create();
  142. CeErpDataSendOrderInfo.createObject(entity.ctid);
  143. }
  144. SqlParameter[] sqlParameter ={
  145. new SqlParameter("@mainctids", SqlDbType.VarChar,500),
  146. new SqlParameter("@userid", SqlDbType.VarChar,4),
  147. new SqlParameter("@res", SqlDbType.VarChar, 4000)
  148. };
  149. sqlParameter[0].Value = dr["ctid"].ToString();
  150. sqlParameter[1].Value = userId;
  151. sqlParameter[2].Direction = ParameterDirection.Output;
  152. CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
  153. }
  154. catch (Exception ex)
  155. {
  156. errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  157. XLog.SaveLog(0, "下载发生错误,ctid:" + dr["ctid"].ToString() + "," + ex.Message);
  158. }
  159. }
  160. }
  161. }
  162. else
  163. {
  164. break;
  165. }
  166. }
  167. if (!hasFile)
  168. {
  169. noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  170. //sql = new StringBuilder();
  171. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid='{0}' ;", dr["ctid"], (int)OrderState.下单完成, 0, "找不到设计文件");
  172. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  173. //conErc("找不到文件,订单号:" + dr["ctid"]);
  174. //return;
  175. }
  176. //if (hasFile)
  177. //{
  178. // fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
  179. // if (File.Exists(fname))
  180. // {
  181. // files.Add(fname);
  182. // copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  183. // }
  184. //}
  185. }
  186. if (fc == 0)
  187. {
  188. conErc("没有找到相关的设计附件");
  189. return;
  190. }
  191. //sql = new StringBuilder();
  192. //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, (int)OrderState.下单完成, userId, "下载设计文件");
  193. //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
  194. //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);
  195. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  196. foreach (string ctid in tArr)
  197. {
  198. CeErpTradeCell.UpdateRelationOrder(ctid);
  199. }
  200. if (Request["supplier"] != null && Request["supplier"].ToString() == "1")
  201. {
  202. ZipFileDownload(files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip");
  203. }
  204. else if (noFileLst.Count > 0 || errorFileLst.Count > 0)
  205. {
  206. string tips = "";
  207. if (noFileLst.Count > 0)
  208. {
  209. string notids = string.Join(",", noFileLst.ToArray());
  210. sql = new StringBuilder();
  211. 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, "找不到设计文件");
  212. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  213. tips += "找不到文件,单号:" + notids;
  214. }
  215. if (errorFileLst.Count > 0)
  216. {
  217. string ertids = string.Join(",", errorFileLst.ToArray());
  218. sql = new StringBuilder();
  219. sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ertids, (int)OrderState.下单完成, 0, "下载设计文件出错");
  220. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  221. tips += " 复制下载出错,单号:" + ertids;
  222. }
  223. conErc(tips);
  224. }
  225. else
  226. {
  227. conSuc("文件已下载到共享目录");
  228. }
  229. return;
  230. }
  231. catch (Exception ex)
  232. {
  233. conErc("复制错误的下载访问");
  234. XLog.SaveLog(0, "copydown" + ex.Message);
  235. return;
  236. }
  237. }
  238. }
  239. private string formatMemo(object memo)
  240. {
  241. string m = memo.ToString();
  242. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  243. return m;
  244. }
  245. Dictionary<string, string> replaceRules = new Dictionary<string, string>
  246. {
  247. { "皙贝", "白卡" },
  248. { "睿狐", "莱尼" },
  249. { "岚蝶", "安格" },
  250. { "琮纹", "刚古" },
  251. { "珠光", "珠光" },
  252. { "溪雪", "珠光" },
  253. { "雅柔", "雅柔" },
  254. { "萱姿", "雅柔" },
  255. { "草香", "草香" },
  256. { "芳怡", "草香" },
  257. { "金绒", "牛皮" },
  258. { "素芸", "棉卡" },
  259. { "玉蕊", "蛋壳" }
  260. };
  261. private void copyFile(string date, string supplier, string file, double payment, string rname)
  262. {
  263. string SupName = supplier;
  264. if (payment >= 500)
  265. {
  266. SupName = supplier + "500";
  267. }
  268. string path = copyPath + "\\" + date + "\\" + SupName;
  269. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  270. string fname = Path.GetFileName(file);
  271. foreach (var rule in replaceRules)
  272. {
  273. fname = fname.Replace(rule.Key, rule.Value);
  274. }
  275. File.Copy(file, path + "\\" + fname, true);
  276. if (!File.Exists(path + "\\" + fname))
  277. {
  278. File.Copy(file, path + "\\" + fname, true);
  279. }
  280. }
  281. private string getDesignTime(object v)
  282. {
  283. if (v.ToString() == "") return "";
  284. return Convert.ToDateTime(v).ToString("yyyyMM");
  285. }
  286. private string getDesignTimeWithDay(object v)
  287. {
  288. if (v.ToString() == "") return "";
  289. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  290. }
  291. private string getDesignDate(object v)
  292. {
  293. return DateTime.Now.ToString("yyyy-MM-dd");
  294. if (v.ToString() == "") return "";
  295. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");
  296. }
  297. /// 批量进行多个文件压缩到一个文件
  298. /// </summary>
  299. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  300. /// <param name="zipFileName">生成的zip文件名称</param>
  301. private void ZipFileDownload(List<string> files, string zipFileName)
  302. {
  303. MemoryStream ms = new MemoryStream();
  304. byte[] buffer = null;
  305. using (ZipFile file = ZipFile.Create(ms))
  306. {
  307. file.BeginUpdate();
  308. //file.NameTransform = new ZipNameTransform();
  309. file.NameTransform = new MyNameTransfom();
  310. foreach (var item in files)
  311. {
  312. if (File.Exists(item)) file.Add(item);
  313. }
  314. file.CommitUpdate();
  315. buffer = new byte[ms.Length];
  316. ms.Position = 0;
  317. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  318. ms.Flush();
  319. ms.Close();
  320. }
  321. Response.Clear();
  322. Response.Buffer = true;
  323. Response.ContentType = "application/x-zip-compressed";
  324. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  325. Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(zipFileName));
  326. Response.BinaryWrite(buffer);
  327. Page.Response.Flush();
  328. Page.Response.SuppressContent = true;
  329. HttpContext.Current.ApplicationInstance.CompleteRequest();
  330. //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
  331. //Response.Flush();
  332. //Response.End();
  333. }
  334. private void downLoadFile(string file)
  335. {
  336. string filePath = Server.MapPath("d/" + file);//路径
  337. //以字符流的形式下载文件
  338. FileStream fs = new FileStream(filePath, FileMode.Open);
  339. byte[] bytes = new byte[(int)fs.Length];
  340. fs.Read(bytes, 0, bytes.Length);
  341. fs.Close();
  342. Response.ContentType = "application/octet-stream";
  343. //通知浏览器下载文件而不是打开
  344. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
  345. Response.BinaryWrite(bytes);
  346. Response.Flush();
  347. Response.End();
  348. }
  349. }