download.aspx.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. using BizCom;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using NPOI.OpenXmlFormats.Shared;
  4. using SiteCore.Redis;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.IO;
  11. using System.Text;
  12. using System.Web;
  13. using System.Web.UI;
  14. public partial class download : System.Web.UI.Page
  15. {
  16. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  17. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  18. public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
  19. private void conErc(string msg)
  20. {
  21. if (msg.IndexOf("访问远程主机") == -1)
  22. {
  23. XLog.SaveLog(0, msg);
  24. }
  25. Response.Write(msg);
  26. //Response.End();
  27. }
  28. private void conSuc(string msg)
  29. {
  30. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  31. //Response.End();
  32. }
  33. protected void Page_Load(object sender, EventArgs e)
  34. {
  35. if (!IsPostBack)
  36. {
  37. Response.Buffer = true;
  38. downloadMore();
  39. }
  40. }
  41. private string getCanDownFile(string fileName)
  42. {
  43. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  44. foreach (string ext in extArr)
  45. {
  46. string fname = fileName + ext;
  47. if (File.Exists(fname))
  48. {
  49. return fname;
  50. }
  51. }
  52. return "";
  53. }
  54. private void updateIsDownSuccess(int userId, string ctid)
  55. {
  56. try
  57. {
  58. SqlParameter[] sqlParameter ={
  59. new SqlParameter("@mainctids", SqlDbType.VarChar,500),
  60. new SqlParameter("@userid", SqlDbType.VarChar,4),
  61. new SqlParameter("@res", SqlDbType.VarChar, 4000)
  62. };
  63. sqlParameter[0].Value = ctid;
  64. sqlParameter[1].Value = userId;
  65. sqlParameter[2].Direction = ParameterDirection.Output;
  66. CeErpTradeCell.ExecuteDataSetStore("sp_set_download", sqlParameter);
  67. CeErpTradeCell.UpdateRelationOrder(ctid);
  68. }
  69. catch (Exception ex)
  70. {
  71. //errorFileLst.Add("'" + dr["ctid"].ToString() + "'");
  72. XLog.SaveLog(0, "下载发生错误,ctid:" + ctid + "," + ex.Message);
  73. }
  74. }
  75. private void downloadMore()
  76. {
  77. if (Request["hexdata"] == null || Request["hexdata"].Trim() == "")
  78. {
  79. conErc("错误的下载访问");
  80. return;
  81. }
  82. string tids = Request["hexdata"];
  83. int onlyDownFile = 0;//只下文件
  84. if (Request["onlyfile"] != null)
  85. {
  86. Int32.TryParse(Request["onlyfile"], out onlyDownFile);
  87. }
  88. int userId = 0;
  89. if (Request["userid"] != null)
  90. {
  91. Int32.TryParse(Request["userid"], out userId);
  92. }
  93. int mvClientDown = 0;//转移到客户端下载
  94. int isFromClient = 0;
  95. if (onlyDownFile != 1)
  96. {
  97. if (Request["supplier"] == null || Request["supplier"].ToString() != "1")//如果不是只下文件,那他就要是供应商
  98. {
  99. conErc("错误的下载访问");
  100. return;
  101. }
  102. else
  103. {
  104. Int32.TryParse(Request["isFromClient"], out isFromClient);
  105. if (userId > 0 && isFromClient != 1)
  106. {
  107. string file_client_down_flg = erpRedis.RedisHelper.StringGet("file_client_down_flg_" + userId);
  108. if (file_client_down_flg != null && file_client_down_flg == "1")
  109. {
  110. mvClientDown = 1;
  111. }
  112. }
  113. }
  114. }
  115. try
  116. {
  117. StringBuilder sql = new StringBuilder();
  118. sql.AppendFormat("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,FileMd5 from view_erptradecell where FinishDesignTime is not null and ctid in ({0}) {1}", ("'" + tids.Replace(",", "','") + "'"), ((onlyDownFile == 1 || isFromClient == 1) ? "" : " and OrderState=5 "));
  119. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  120. if (dt == null || dt.Rows.Count < 1)
  121. {
  122. conErc("没有找到相关订单");
  123. return;
  124. }
  125. string fileMd5 = "", fileNames = "";
  126. List<string> files = new List<string>();
  127. List<string> noFileLst = new List<string>();
  128. List<string> ctidLst = new List<string>();
  129. foreach (DataRow dr in dt.Rows)
  130. {
  131. string finishDesignTime = "";
  132. DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
  133. DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
  134. if (ftime.CompareTo(splitTime) > 0)
  135. {
  136. finishDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);//这个时间以后得按天分文件夹
  137. }
  138. else
  139. {
  140. finishDesignTime = getDesignTime(dr["FinishDesignTime"]);//上传原来按月分文件夹
  141. }
  142. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(dr["seller_memo"]);
  143. string fname = getCanDownFile(df_name);
  144. if (string.IsNullOrEmpty(fname))
  145. {
  146. noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  147. continue;
  148. }
  149. files.Add(fname);
  150. ctidLst.Add(dr["ctid"].ToString());
  151. fileMd5 += "," + dr["FileMd5"].ToString();
  152. fileNames += "#$#" + Path.GetFileName(fname);
  153. if (onlyDownFile != 1 && mvClientDown != 1)
  154. copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  155. }
  156. if (files.Count == 0)
  157. {
  158. conErc("没有找到相关的设计附件");
  159. return;
  160. }
  161. if (noFileLst.Count > 0)
  162. {
  163. string tips = "";
  164. string notids = string.Join(",", noFileLst.ToArray());
  165. sql = new StringBuilder();
  166. 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, "找不到设计文件");
  167. CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  168. tips += "找不到文件,单号:" + notids;
  169. conErc(tips);
  170. return;
  171. }
  172. if (mvClientDown == 1)
  173. {
  174. for (int i = 0; i < files.Count; i++)
  175. {
  176. if (onlyDownFile != 1)
  177. updateIsDownSuccess(userId, ctidLst[i]);
  178. }
  179. string key = "file_client_down_list_" + userId;
  180. string data = "{\"hexdata\":\"" + tids + "\",\"fileMd5\":\"" + fileMd5.Substring(1) + "\",\"supplier\":\""
  181. + (Request["supplier"] != null ? Request["supplier"].ToString() : "0") + "\",\"fileName\":\"" + System.Web.HttpUtility.UrlEncode(fileNames, System.Text.Encoding.GetEncoding("GB2312")) + "\"}";
  182. erpRedis.RedisHelper.ListLeftPush(key, data);
  183. return;
  184. }
  185. if (files.Count == 1)
  186. {
  187. downLoadFile(userId, ctidLst[0], files[0], onlyDownFile, isFromClient);
  188. }
  189. else
  190. {
  191. ZipFileDownload(userId, ctidLst, files, "LT_" + DateTime.Now.ToString("yyyyMMddhhMmss") + ".zip", onlyDownFile, isFromClient); //downLoadFile(userId, ctidLst[i], files[i]);
  192. }
  193. //conSuc("文件已下载完成");
  194. return;
  195. }
  196. catch (Exception ex)
  197. {
  198. conErc("错误的下载访问" + ex.Message);
  199. return;
  200. }
  201. }
  202. private string formatMemo(object memo)
  203. {
  204. string m = memo.ToString();
  205. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  206. return m;
  207. }
  208. private void copyFile(string date, string supplier, string file)
  209. {
  210. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  211. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  212. string fname = Path.GetFileName(file);
  213. File.Copy(file, path + "\\" + fname, true);
  214. if (!File.Exists(path + "\\" + fname))
  215. {
  216. File.Copy(file, path + "\\" + fname, true);
  217. }
  218. }
  219. private string getDesignTime(object v)
  220. {
  221. if (v.ToString() == "") return "";
  222. return Convert.ToDateTime(v).ToString("yyyyMM");
  223. }
  224. private string getDesignTimeWithDay(object v)
  225. {
  226. if (v.ToString() == "") return "";
  227. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  228. }
  229. private string getDesignDate(object v)
  230. {
  231. return DateTime.Now.ToString("yyyy-MM-dd");
  232. /*if (v.ToString() == "") return "";
  233. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  234. }
  235. /// 批量进行多个文件压缩到一个文件
  236. /// </summary>
  237. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  238. /// <param name="zipFileName">生成的zip文件名称</param>
  239. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
  240. {
  241. MemoryStream ms = new MemoryStream();
  242. byte[] buffer = null;
  243. using (ZipFile file = ZipFile.Create(ms))
  244. {
  245. file.BeginUpdate();
  246. //file.NameTransform = new ZipNameTransform();
  247. file.NameTransform = new MyNameTransfom();
  248. foreach (var item in files)
  249. {
  250. if (File.Exists(item)) file.Add(item);
  251. }
  252. file.CommitUpdate();
  253. buffer = new byte[ms.Length];
  254. ms.Position = 0;
  255. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  256. ms.Flush();
  257. ms.Close();
  258. }
  259. Response.Clear();
  260. Response.Buffer = true;
  261. Response.ContentType = "application/x-zip-compressed";
  262. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  263. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipFileName));
  264. Response.BinaryWrite(buffer);
  265. Page.Response.Flush();
  266. for (int i = 0; i < files.Count; i++)
  267. {
  268. if (onlyDownFile != 1 && isFromClient != 1)
  269. updateIsDownSuccess(userId, ctidLst[i]);
  270. }
  271. }
  272. //public static object downfileObj = new object();
  273. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
  274. {
  275. string filePath = file;
  276. string dfile = Path.GetFileName(file);
  277. FileStream fs = new FileStream(filePath, FileMode.Open);
  278. byte[] bytes = new byte[(int)fs.Length];
  279. fs.Read(bytes, 0, bytes.Length);
  280. fs.Close();
  281. Response.Clear();
  282. //
  283. Response.ClearContent();
  284. Response.ClearHeaders();
  285. Response.ContentType = "application/octet-stream";
  286. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  287. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  288. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  289. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
  290. Response.AddHeader("Content-Length", bytes.Length.ToString());
  291. Response.BinaryWrite(bytes);
  292. Response.Flush();
  293. if (onlyDownFile != 1 && isFromClient != 1)
  294. updateIsDownSuccess(userId, ctid);
  295. }
  296. }