supplierBuildFile.aspx.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. using Aliyun.OSS;
  2. using Aliyun.OSS.Common;
  3. using BizCom;
  4. using ICSharpCode.SharpZipLib.Zip;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.IO.Compression;
  12. using System.Runtime.InteropServices;
  13. using System.Security.Principal;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Web;
  18. public partial class supplierBuildFile : System.Web.UI.Page
  19. {
  20. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  21. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  22. public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
  23. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  24. public static extern uint DecFile(string filename);
  25. [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
  26. public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
  27. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  28. public static extern void CreateUserKey(StringBuilder key, int len);
  29. [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
  30. public static extern int InitAesKey(StringBuilder key, int len);
  31. [DllImport("DrvInterface64.dll")]
  32. public static extern int IsInitedAesKey();
  33. private void conErc(string msg)
  34. {
  35. XLog.SaveLog(0, msg);
  36. Response.Write(msg);
  37. //Response.StatusCode = (int)HttpStatusCode.NotFound;
  38. //Response.End();
  39. }
  40. private void conSuc(string msg)
  41. {
  42. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  43. //Response.End();
  44. }
  45. protected void Page_Load(object sender, EventArgs e)
  46. {
  47. if (!IsPostBack)
  48. {
  49. Response.Buffer = true;
  50. downloadMore();
  51. }
  52. }
  53. private string getCanDownFile(string fileName)
  54. {
  55. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  56. foreach (string ext in extArr)
  57. {
  58. string fname = fileName + ext;
  59. if (File.Exists(fname))
  60. {
  61. return ext;
  62. }
  63. }
  64. return "";
  65. }
  66. static bool running = false;
  67. private void downloadMore()
  68. {
  69. if (running)
  70. {
  71. conSuc("运行中!");
  72. return;
  73. }
  74. running = true;
  75. var identity = WindowsIdentity.GetCurrent();
  76. var principal = new WindowsPrincipal(identity);
  77. Task.Run(async () =>
  78. {
  79. using (identity.Impersonate())
  80. {
  81. StringBuilder sql = new StringBuilder();
  82. sql.AppendFormat("select * from CE_ErpPackData WITH(nolock) where upStatus = 0");
  83. int userId = 1;
  84. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  85. string updateSql = "";
  86. if (dt != null && dt.Rows.Count > 0)
  87. {
  88. foreach (DataRow dr in dt.Rows)
  89. {
  90. string zipFileName = dr["fileName"].ToString();
  91. int supplierId = 0;
  92. string packId = dr["ID"].ToString();
  93. try
  94. {
  95. CeErpTradeLog.ExecuteNonQuery(string.Format("update CE_ErpPackData set upStatus = 1 where ID= {0} ;", packId));
  96. DataTable itemData = CeErpTradeCell.ExecuteDataset(string.Format("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,OrderSn,tid,SupplierId from view_erptradecell where FinishDesignTime is not null and ctid in (SELECT ctid FROM CE_ErpPackDataItem WHERE packId = {0})", packId)).Tables[0];
  97. List<string> files = new List<string>();
  98. List<string> tids = new List<string>();
  99. int upStatus = 3;
  100. string url = "";
  101. if (itemData != null && itemData.Rows.Count > 0)
  102. {
  103. string suppierName = "";
  104. foreach (DataRow row in itemData.Rows)
  105. {
  106. supplierId = Convert.ToInt32(row["SupplierId"].ToString());
  107. string finishDesignTime = getDesignTime(row["FinishDesignTime"]);
  108. string ctid = row["ctid"].ToString();
  109. string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(row["seller_memo"]);
  110. string ext = getCanDownFile(df_name);
  111. suppierName = row["SupplierName"].ToString();
  112. if (string.IsNullOrEmpty(ext))
  113. {
  114. //不存在则打包失败
  115. updateSql += string.Format("update CE_ErpPackDataItem set message = '文件不存在!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  116. files = new List<string>();
  117. supplierId = 0;
  118. break;
  119. }
  120. string fname = df_name + ext;
  121. if (Convert.ToInt16(row["OrderState"]) != 6)
  122. {
  123. updateSql += string.Format("update CE_ErpPackDataItem set message = '订单状态不正确!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  124. continue;
  125. }
  126. int IsFileEncrypt = IsFileEncrypted(fname);
  127. if (IsFileEncrypt == 1 && File.Exists(fname))
  128. {
  129. string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
  130. var sb = new StringBuilder(key);
  131. //Linux系统的接口要调用一次,Windows系统要调用两次
  132. CreateUserKey(sb, key.Length);
  133. CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
  134. int result = InitAesKey(sb, sb.Length);
  135. result = IsInitedAesKey();
  136. if (result != 1)
  137. {
  138. addLog(ctid, userId, "初始化秘钥失败" + result, 0);
  139. updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  140. continue;
  141. }
  142. uint a = DecFile(fname);
  143. if (a != 0)
  144. {
  145. addLog(ctid, userId, "解密失败" + a, 0);
  146. updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  147. continue;
  148. }
  149. }
  150. if (string.IsNullOrEmpty(fname))
  151. {
  152. updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
  153. continue;
  154. }
  155. try
  156. {
  157. copyFile(getDesignDate(row["FinishDesignTime"]), suppierName, fname, zipFileName.Replace(".zip", ""));
  158. files.Add(fname);
  159. supplierId = 0;
  160. tids.Add("'" + ctid + "'");
  161. }
  162. catch (Exception ex)
  163. {
  164. writeLog("打包复制文件出错!" + ex.Message);
  165. updateSql += string.Format("update CE_ErpPackDataItem set message = '复制文件出错!{2}' where packId= {0} and ctid='{1}' ;", packId, ctid, ex.Message);
  166. files = new List<string>();//清空数据
  167. supplierId = 0;
  168. break;
  169. }
  170. }
  171. if (files.Count == 0)
  172. {
  173. updateSql += string.Format("update CE_ErpPackData set upStatus = 3,message='没有可打包文件!' where ID= {0} ;", packId);
  174. continue;
  175. }
  176. else
  177. {
  178. string sourceFolder = getCopyPath(getDesignDate(""), suppierName, zipFileName.Replace(".zip", ""));
  179. string zipFilePath = getCopyPath(getDesignDate(""), suppierName) + "\\" + zipFileName;
  180. ZipLargeFolder(sourceFolder, zipFilePath, supplierId);
  181. url = FileOssUpV2(zipFilePath, zipFileName);
  182. if (url != null)
  183. {
  184. upStatus = 2;
  185. updateSql += string.Format("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", string.Join(",", tids), (int)OrderState.下单完成, 0, "下载设计文件");
  186. updateSql += string.Format("update ce_erptradecell set UpdateTime=getdate() where ctid in ({0}) ;", string.Join(",", tids));
  187. }
  188. }
  189. }
  190. updateSql += string.Format("update CE_ErpPackData set upStatus = {1},fileUrl='{2}' where ID= {0} ;", packId, upStatus, url);
  191. }
  192. catch (Exception ex)
  193. {
  194. writeLog("打包文件出错!" + ex.Message);
  195. updateSql += string.Format("update CE_ErpPackData set upStatus = 3 where ID= {0} ;", packId);
  196. }
  197. CeErpTradeLog.ExecuteNonQuery(updateSql);
  198. updateSql = "";
  199. }
  200. }
  201. running = false;
  202. }
  203. });
  204. conSuc("运行结束!");
  205. //FileOssUp();
  206. }
  207. private static string dealMemoName(string name)
  208. {
  209. string[] al = name.Split('-');
  210. List<string> list = new List<string>();
  211. string pa = string.Empty;
  212. for (int i = 0; i < al.Length; i++)
  213. {
  214. if (i == 1)
  215. {
  216. if (al[i].Contains("(") || al[i].Contains("("))
  217. {
  218. string tname = al[i].Replace(")", "").Replace(")", "").Replace("(", "").Replace("(", "");
  219. if (!string.IsNullOrEmpty(tname))
  220. {
  221. pa = al[i];
  222. }
  223. continue;
  224. }
  225. }
  226. list.Add(al[i]);
  227. }
  228. if (!string.IsNullOrEmpty(pa))
  229. {
  230. list.Insert(3, pa);
  231. }
  232. name = string.Join("-", list);
  233. return name;
  234. }
  235. private string formatMemo(object memo)
  236. {
  237. string m = memo.ToString();
  238. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  239. return m;
  240. }
  241. private void copyFile(string date, string supplier, string file, string zipName = "")
  242. {
  243. string path = getCopyPath(date, supplier, zipName);
  244. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  245. string fname = Path.GetFileName(file);
  246. File.Copy(file, path + "\\" + fname, true);
  247. if (!File.Exists(path + "\\" + fname))
  248. {
  249. File.Copy(file, path + "\\" + fname, true);
  250. }
  251. }
  252. private string getCopyPath(string date, string supplier, string zipName = "")
  253. {
  254. string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
  255. if (!string.IsNullOrEmpty(zipName))
  256. {
  257. path = path + "\\" + zipName;
  258. }
  259. return path;
  260. }
  261. private string getDesignTime(object v)
  262. {
  263. if (v.ToString() == "") return "";
  264. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  265. }
  266. private string getDesignDate(object v)
  267. {
  268. int year = DateTime.Now.Year;
  269. int month = DateTime.Now.Month;
  270. int day = DateTime.Now.Day;
  271. return year + "\\" + month + "\\" + day;
  272. /*if (v.ToString() == "") return "";
  273. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
  274. }
  275. private string FileOssUp(byte[] buffer, string fileName)
  276. {
  277. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  278. var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
  279. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  280. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  281. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  282. // 填写Bucket名称,例如examplebucket。
  283. var bucketName = "ltcloudfile";
  284. int year = DateTime.Now.Year;
  285. int month = DateTime.Now.Month;
  286. int day = DateTime.Now.Day;
  287. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  288. var objectName = "supplierFile/" + year + "/" + month + "/" + day + "/" + fileName;
  289. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  290. string region = "cn-hangzhou";
  291. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  292. var conf = new ClientConfiguration();
  293. // 设置v4签名。
  294. conf.SignatureVersion = SignatureVersion.V4;
  295. // 创建OssClient实例。
  296. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  297. client.SetRegion(region);
  298. try
  299. {
  300. MemoryStream requestContent = new MemoryStream(buffer);
  301. // 上传文件。
  302. client.PutObject(bucketName, objectName, requestContent);
  303. }
  304. catch (Exception ex)
  305. {
  306. writeLog("打包文件上传oss出错!" + ex.Message);
  307. return null;
  308. }
  309. return "https://ltcloudfile.oss-cn-hangzhou.aliyuncs.com/" + objectName;
  310. }
  311. private string FileOssUpV2(string filePath, string fileName)
  312. {
  313. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  314. var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
  315. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  316. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  317. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  318. // 填写Bucket名称,例如examplebucket。
  319. var bucketName = "ltcloudfile";
  320. int year = DateTime.Now.Year;
  321. int month = DateTime.Now.Month;
  322. int day = DateTime.Now.Day;
  323. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  324. var objectName = "supplierFile/" + year + "/" + month + "/" + day + "/" + fileName;
  325. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  326. string region = "cn-hangzhou";
  327. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  328. var conf = new ClientConfiguration();
  329. // 设置v4签名。
  330. conf.SignatureVersion = SignatureVersion.V4;
  331. // 创建OssClient实例。
  332. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  333. client.SetRegion(region);
  334. var uploadId = "";
  335. try
  336. {
  337. // 定义上传的文件及所属Bucket的名称。您可以在InitiateMultipartUploadRequest中设置ObjectMeta,但不必指定其中的ContentLength。
  338. var request = new InitiateMultipartUploadRequest(bucketName, objectName);
  339. var result = client.InitiateMultipartUpload(request);
  340. uploadId = result.UploadId;
  341. }
  342. catch (Exception ex)
  343. {
  344. writeLog("Init multi part upload failed, {0}" + ex.Message);
  345. Environment.Exit(1);
  346. }
  347. // 计算分片总数。
  348. // 分片最小值为100 KB,最大值为5 GB。最后一个分片的大小允许小于100 KB。
  349. var partSize = 10 * 1024 * 1024;
  350. var fi = new FileInfo(filePath);
  351. var fileSize = fi.Length;
  352. var partCount = fileSize / partSize;
  353. if (fileSize % partSize != 0)
  354. {
  355. partCount++;
  356. }
  357. var partETags = new List<PartETag>();
  358. try
  359. {
  360. using (var fs = File.Open(filePath, FileMode.Open))
  361. {
  362. for (var i = 0; i < partCount; i++)
  363. {
  364. var skipBytes = (long)partSize * i;
  365. // 定位到本次上传的起始位置。
  366. fs.Seek(skipBytes, 0);
  367. // 计算本次上传的分片大小,最后一片为剩余的数据大小。
  368. var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
  369. var request = new UploadPartRequest(bucketName, objectName, uploadId)
  370. {
  371. InputStream = fs,
  372. PartSize = size,
  373. PartNumber = i + 1
  374. };
  375. // 调用UploadPart接口执行上传功能,返回结果中包含了这个数据片的ETag值。
  376. var result = client.UploadPart(request);
  377. partETags.Add(result.PartETag);
  378. writeLog(string.Format(fileName + ":finish {0}/{1}", partETags.Count, partCount));
  379. }
  380. writeLog(string.Format(fileName + ":Put multi part upload succeeded"));
  381. }
  382. }
  383. catch (Exception ex)
  384. {
  385. writeLog(string.Format("Put multi part upload failed, {0}", ex.Message));
  386. Environment.Exit(1);
  387. }
  388. // 当分片上传成功后,合并分片。
  389. try
  390. {
  391. var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
  392. foreach (var partETag in partETags)
  393. {
  394. completeMultipartUploadRequest.PartETags.Add(partETag);
  395. }
  396. var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
  397. }
  398. catch (Exception ex)
  399. {
  400. writeLog(string.Format("complete multi part failed, {0}", ex.Message));
  401. Environment.Exit(1);
  402. }
  403. return "https://ltcloudfile.oss-cn-hangzhou.aliyuncs.com/" + objectName;
  404. }
  405. /// 批量进行多个文件压缩到一个文件
  406. /// </summary>
  407. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  408. /// <param name="zipFileName">生成的zip文件名称</param>
  409. private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
  410. {
  411. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  412. var endpoint = "https://oss-cn-fuzhou.aliyuncs.com";
  413. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  414. var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
  415. var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
  416. // 填写Bucket名称,例如examplebucket。
  417. var bucketName = "dfdiyfile";
  418. // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
  419. var objectName = "exampledir/exampleobject.txt";
  420. // 填写字符串。
  421. var objectContent = "More than just cloud.";
  422. // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
  423. const string region = "oss-cn-fuzhou";
  424. // 创建ClientConfiguration实例,按照您的需要修改默认参数。
  425. var conf = new ClientConfiguration();
  426. // 设置v4签名。
  427. conf.SignatureVersion = SignatureVersion.V4;
  428. // 创建OssClient实例。
  429. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
  430. client.SetRegion(region);
  431. try
  432. {
  433. MemoryStream ms = new MemoryStream();
  434. byte[] buffer = null;
  435. using (ZipFile file = ZipFile.Create(ms))
  436. {
  437. file.BeginUpdate();
  438. //file.NameTransform = new ZipNameTransform();
  439. file.NameTransform = new MyNameTransfom();
  440. file.Add("C:\\Users\\231010\\Downloads\\setup.exe");
  441. file.CommitUpdate();
  442. buffer = new byte[ms.Length];
  443. ms.Position = 0;
  444. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  445. ms.Flush();
  446. ms.Close();
  447. }
  448. MemoryStream requestContent = new MemoryStream(buffer);
  449. // 上传文件。
  450. client.PutObject(bucketName, objectName, requestContent);
  451. Console.WriteLine("Put object succeeded");
  452. }
  453. catch (Exception ex)
  454. {
  455. Console.WriteLine("Put object failed, {0}", ex.Message);
  456. }
  457. conSuc("上传成功!");
  458. return;
  459. //for (int i = 0; i < addFiles.Count; i++)
  460. //{
  461. // updateIsDownSuccess(userId, addCtid[i]);
  462. //}
  463. //StringBuilder sql = new StringBuilder();
  464. //string tids = string.Join(",", addCtid);
  465. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  466. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  467. //sql = new StringBuilder();
  468. //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, "下载设计文件");
  469. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  470. }
  471. //public static object downfileObj = new object();
  472. private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
  473. {
  474. string filePath = file;
  475. string dfile = Path.GetFileName(file);
  476. FileStream fs = new FileStream(filePath, FileMode.Open);
  477. byte[] bytes = new byte[(int)fs.Length];
  478. fs.Read(bytes, 0, bytes.Length);
  479. fs.Close();
  480. Response.Clear();
  481. //
  482. Response.ClearContent();
  483. Response.ClearHeaders();
  484. Response.ContentType = "application/octet-stream";
  485. //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
  486. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
  487. //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
  488. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
  489. Response.AddHeader("Content-Length", bytes.Length.ToString());
  490. Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
  491. Response.BinaryWrite(bytes);
  492. Response.Flush();
  493. //updateIsDownSuccess(userId, ctid);
  494. //StringBuilder sql = new StringBuilder();
  495. //string tids = string.Join(",", ctid);
  496. //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
  497. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  498. //sql = new StringBuilder();
  499. //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, "下载设计文件");
  500. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  501. }
  502. /// <summary>
  503. /// 压缩大文件夹(分块处理)
  504. /// </summary>
  505. public static void ZipLargeFolder(string sourceFolder, string zipFilePath, int supplierId, CompressionLevel compressionLevel = CompressionLevel.Optimal)
  506. {
  507. // 参数验证
  508. if (string.IsNullOrEmpty(sourceFolder))
  509. throw new ArgumentNullException("sourceFolder", "源文件夹路径不能为空");
  510. if (string.IsNullOrEmpty(zipFilePath))
  511. throw new ArgumentNullException("zipFilePath", "压缩文件路径不能为空");
  512. if (!Directory.Exists(sourceFolder))
  513. {
  514. throw new DirectoryNotFoundException("源文件夹不存在: " + sourceFolder);
  515. }
  516. // 确保目标目录存在
  517. var zipDir = Path.GetDirectoryName(zipFilePath);
  518. if (!string.IsNullOrEmpty(zipDir) && !Directory.Exists(zipDir))
  519. {
  520. Directory.CreateDirectory(zipDir);
  521. }
  522. if (File.Exists(zipFilePath))
  523. {
  524. File.Delete(zipFilePath);
  525. }
  526. // 使用 EnumerateFiles 减少内存使用
  527. var files = Directory.EnumerateFiles(sourceFolder, "*.*", SearchOption.AllDirectories);
  528. using (var fileStream = new FileStream(zipFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192))
  529. using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
  530. {
  531. foreach (var file in files)
  532. {
  533. try
  534. {
  535. string fileName = Path.GetFileName(file);
  536. if (supplierId == 14)
  537. {
  538. fileName = dealMemoName(fileName);
  539. }
  540. // 获取相对路径
  541. string relativePath = GetRelativePath(sourceFolder, file);
  542. // 创建zip条目
  543. var entry = zipArchive.CreateEntry(fileName, compressionLevel);
  544. // 使用流写入文件内容
  545. using (var entryStream = entry.Open())
  546. using (var stream = File.OpenRead(file))
  547. {
  548. // 使用更大的缓冲区提高性能
  549. stream.CopyTo(entryStream, 81920);
  550. }
  551. }
  552. catch (Exception ex)
  553. {
  554. // 记录错误但继续处理其他文件
  555. writeLog("压缩文件失败: 错误: " + ex);
  556. }
  557. }
  558. }
  559. }
  560. // 辅助方法:获取相对路径
  561. private static string GetRelativePath(string basePath, string fullPath)
  562. {
  563. Uri baseUri = new Uri(basePath + Path.DirectorySeparatorChar);
  564. Uri fullUri = new Uri(fullPath);
  565. Uri relativeUri = baseUri.MakeRelativeUri(fullUri);
  566. return Uri.UnescapeDataString(relativeUri.ToString()).Replace('\\', '/');
  567. }
  568. public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
  569. {
  570. CeErpTradeLog log = new CeErpTradeLog();
  571. log.tid = ctid;
  572. log.UserId = userid;
  573. log.Con = con;
  574. log.OrderState = orderState;
  575. log.AfterSaleState = aftersaleState;
  576. log.OperateTime = DateTime.Now;
  577. log.Create();
  578. }
  579. private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
  580. private static object logFlag = new object();
  581. public static void writeLog(string log)
  582. {
  583. lock (logFlag)
  584. {
  585. using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
  586. {
  587. using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
  588. {
  589. sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
  590. sw.Flush();
  591. }
  592. }
  593. }
  594. }
  595. }