You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

570 lines
21 KiB

2 years ago
  1. <%@ WebHandler Language="C#" Class="WebHandler" %>
  2. using System;
  3. using System.Web;
  4. using System.IO;
  5. using System.Drawing;
  6. using System.Drawing.Imaging;
  7. using System.Drawing.Drawing2D;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using EasyBL;
  11. using EasyNet;
  12. using Entity.Sugar;
  13. using SqlSugar.Base;
  14. using System.Web.SessionState;
  15. public class WebHandler : IHttpHandler, IRequiresSessionState
  16. {
  17. string default_w = "120";
  18. string default_h = "76";
  19. int iwidth;
  20. int iheight;
  21. bool parseOk = false;
  22. public void ProcessRequest(HttpContext context)
  23. {
  24. //Handler action = null;
  25. var req = context.Request;
  26. var sAction = req["action"];
  27. switch (sAction)
  28. {
  29. case "downfile":
  30. downFile(context);
  31. break;
  32. case "saveimg":
  33. SaveImg(context);
  34. break;
  35. case "uploadfile":
  36. UploadFile(context);
  37. break;
  38. case "securityimg":
  39. SecurityImg(context);
  40. break;
  41. default:
  42. break;
  43. }
  44. //action.Process();
  45. }
  46. #region UploadFile 上傳文件
  47. public void UploadFile(HttpContext context)
  48. {
  49. var req = context.Request;
  50. var sSource = req["source"];
  51. var sOrgID = req["orgid"];
  52. var sUserID = req["userid"];
  53. var sParentID = req["parentid"];
  54. var sServerPath = HttpContext.Current.Server.MapPath("/");
  55. var sRoot = sServerPath + "Document\\EurotranFile";
  56. Common.FnCreateDir(sRoot + "\\" + sSource);//如果沒有該目錄就創建目錄
  57. var CheckFile = req.Files[0].FileName; //檔案名稱
  58. if (CheckFile != "")
  59. {
  60. var list_Add = new List<OTB_SYS_Files>();
  61. for (int index = 0; index < req.Files.Count; index++)
  62. {
  63. var file = req.Files[index];
  64. var sFileSizeName = "";
  65. var sFileID = Guid.NewGuid().ToString();//檔案ID
  66. var sFileName = Path.GetFileName(file.FileName);//檔案名稱+文件格式名稱
  67. var sFileType = file.ContentType; //檔案類型
  68. var iFileSize = file.ContentLength; //檔案大小
  69. var KBSize = Math.Round((decimal)iFileSize / 1024, 1);//單位KB
  70. if (KBSize < 1024)
  71. {
  72. sFileSizeName = KBSize + "KB";
  73. }
  74. else
  75. {
  76. var ComparisonSize = Math.Round((decimal)KBSize / 1024, 1);//單位MB
  77. sFileSizeName = ComparisonSize + "MB";
  78. }
  79. var sfileName = sFileName.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
  80. var sSubFileName = sfileName.LastOrDefault(); //副檔名
  81. var sNewFileName = sFileID + '.' + sSubFileName;
  82. var sOutputPath = sRoot + "/" + sSource + "/" + sNewFileName;
  83. sOutputPath = System.Text.RegularExpressions.Regex.Replace(sOutputPath, @"//|/", @"\");
  84. file.SaveAs(sOutputPath);
  85. var oFile = new OTB_SYS_Files
  86. {
  87. OrgID = sOrgID,
  88. FileID = sFileID,
  89. ParentID = sParentID,
  90. SourceFrom = sSource,
  91. FileName = sFileName,
  92. SubFileName = sSubFileName,
  93. FilePath = sOutputPath.Replace(sServerPath, ""),
  94. FileType = sFileType,
  95. FileSize = iFileSize,
  96. FileSizeName = sFileSizeName,
  97. CreateUser = sUserID,
  98. CreateDate = DateTime.Now,
  99. ModifyUser = sUserID,
  100. ModifyDate = DateTime.Now
  101. };
  102. list_Add.Add(oFile);
  103. }
  104. var db = SugarBase.DB;
  105. var iRes = db.Insertable(list_Add.ToArray()).ExecuteCommand();
  106. }
  107. }
  108. #endregion
  109. #region downFile 下載文件
  110. public void downFile(HttpContext c)
  111. {
  112. var req = c.Request;
  113. var sPath = req["path"];
  114. var sCusFileName = req["filename"];
  115. sPath = System.Text.RegularExpressions.Regex.Replace(sPath, @"//|/", @"\");
  116. var sServerPath = c.Server.MapPath("/");
  117. sPath = sPath.Replace(sServerPath, "");
  118. sPath = c.Server.MapPath(sPath);
  119. var sFileName = "";
  120. var sExtName = "";
  121. if (!File.Exists(sPath))
  122. {
  123. return;
  124. }
  125. if (sPath != null)
  126. {
  127. var index = 0;
  128. index = sPath.IndexOf("OutFiles");
  129. if (index == -1)
  130. {
  131. index = sPath.IndexOf("EurotranFile");
  132. }
  133. var sNewPath = sPath.Substring(index);
  134. var saPath = sNewPath.Split('.');
  135. var saNewPath = saPath[0].Split("\\/".ToCharArray());
  136. sExtName = saPath[1];
  137. sFileName = sCusFileName ?? saNewPath[saNewPath.Length - 1];
  138. }
  139. c.Response.ContentType = "application/octet-stream";
  140. //设置响应的返回类型是文件流
  141. c.Response.AddHeader("content-disposition", "attachment;filename=" + sFileName + "." + sExtName);
  142. //设置相应的头以及被下载时候显示的文件名
  143. var lFileInfo = new FileInfo(sPath);
  144. //获取下载文件的文件流
  145. c.Response.WriteFile(lFileInfo.FullName);
  146. //返回要下载的文件流
  147. c.Response.End();
  148. }
  149. #endregion
  150. #region SaveImg 儲存圖片
  151. public void SaveImg(HttpContext c)
  152. {
  153. c.Response.ContentType = "text/plain";
  154. var strfilepath = HttpUtility.UrlDecode(c.Request.Form["filepath"], System.Text.Encoding.UTF8);
  155. var phy = HttpUtility.UrlDecode(c.Request.Form["phy"], System.Text.Encoding.UTF8);
  156. var filename = HttpUtility.UrlDecode(c.Request.Form["filename"], System.Text.Encoding.UTF8);
  157. var isrepeat = HttpUtility.UrlDecode(c.Request.Form["isrepeat"], System.Text.Encoding.UTF8);
  158. var user = HttpUtility.UrlDecode(c.Request.Form["user"], System.Text.Encoding.UTF8);
  159. var oDocument_model = new OTB_SYS_Document();
  160. var TopPath = "Document";
  161. var fileroot = "";
  162. try
  163. {
  164. if (phy == "false")
  165. {
  166. //不是實體路徑
  167. //取得實體路徑
  168. strfilepath = HttpContext.Current.Request.MapPath(strfilepath);
  169. }
  170. fileroot = ("\\" + strfilepath.Substring(strfilepath.IndexOf(TopPath))).Replace("\\", "/");
  171. fileroot = fileroot.Substring(0, 1) != "/" ? "/" + fileroot : fileroot; //如果開頭沒有斜線就加上斜線
  172. fileroot = fileroot.Substring(fileroot.Length - 1) != "/" ? fileroot + "/" : fileroot; //如果尾端沒有斜線就加上斜線
  173. var f_name = Path.GetFileNameWithoutExtension(filename);
  174. var f_extn = Path.GetExtension(filename);
  175. var gu_id = Guid.NewGuid().ToString(); //新增圖片GUID
  176. var stringToBase64 = ""; //儲存縮小圖的base64字串
  177. oDocument_model.GUID = gu_id;
  178. oDocument_model.FileName = f_name;
  179. oDocument_model.SubFileName = f_extn;
  180. oDocument_model.FileRoot = fileroot;
  181. oDocument_model.FilePath = fileroot + filename;
  182. var newfile = new FileInfo(strfilepath + filename);
  183. oDocument_model.FileSize = (int)newfile.Length / 1024; //圖片大小
  184. #region base64string 縮圖處理
  185. using (var ms = new MemoryStream())
  186. {
  187. using (var fs = new FileStream(newfile.FullName, FileMode.Open))
  188. {
  189. using (var img = System.Drawing.Image.FromStream(fs))
  190. {
  191. oDocument_model.PixelW = img.Width;
  192. oDocument_model.PixelH = img.Height;
  193. var intW = 100;
  194. var intH = 100;
  195. if (img.Width > img.Height)
  196. {
  197. intW = 100;
  198. intH = (int)100 * img.Height / img.Width;
  199. }
  200. else
  201. {
  202. intH = 100;
  203. intW = (int)100 * img.Width / img.Height;
  204. }
  205. using (var NewImage = new System.Drawing.Bitmap(intW, intH))
  206. {
  207. using (var g = System.Drawing.Graphics.FromImage(NewImage))
  208. {
  209. g.DrawImage(img, 0, 0, intW, intH);
  210. NewImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  211. var imageBytes = ms.ToArray();
  212. stringToBase64 = Convert.ToBase64String(imageBytes);
  213. oDocument_model.FileContent = "data:image/jpg;base64," + stringToBase64;
  214. }
  215. }
  216. }
  217. }
  218. }
  219. #endregion
  220. oDocument_model.IsProtected = "N"; //是否能複製、移除
  221. oDocument_model.IsPublic = "N"; //是否共用
  222. oDocument_model.Memo = (fileroot + filename).Replace("/", " "); //關鍵字查詢
  223. oDocument_model.FileCreateDate = newfile.CreationTime; //檔案創建日
  224. oDocument_model.CreateUser = !string.IsNullOrEmpty(user) ? user : "apadmin"; //創建人
  225. oDocument_model.ModifyUser = !string.IsNullOrEmpty(user) ? user : "apadmin"; //修改人
  226. var db = SugarBase.GetIntance();
  227. if (isrepeat == "true")
  228. {
  229. //修改
  230. var oDoc = db.Queryable<OTB_SYS_Document>().Single(it => it.FilePath == fileroot + filename && it.status != 99);
  231. if (oDoc != null)
  232. {
  233. //有查到GUID才更新圖檔
  234. var iEffect_Upd = db.Updateable(oDocument_model).Where(it => it.GUID == oDoc.GUID).ExecuteCommand();
  235. if (iEffect_Upd > 0)
  236. {
  237. c.Response.Write(oDocument_model.GUID); //儲存成功傳回圖檔GUID
  238. }
  239. }
  240. else
  241. {
  242. //沒有找到相對GUID就新增新增
  243. var iEffect_Add = db.Insertable(oDocument_model).ExecuteCommand();
  244. if (iEffect_Add > 0)
  245. {
  246. c.Response.Write(oDocument_model.GUID); //儲存成功傳回圖檔GUID
  247. }
  248. }
  249. }
  250. else
  251. {
  252. //新增
  253. var iEffect = db.Insertable(oDocument_model).ExecuteCommand();
  254. if (iEffect > 0)
  255. {
  256. c.Response.Write(oDocument_model.GUID); //儲存成功傳回圖檔GUID
  257. }
  258. }
  259. }
  260. catch (Exception ex)
  261. {
  262. LogService.mo_Log.Error("Controller.SaveImg Error Message:" + ex.Message, ex);
  263. c.Response.Write("0"); //儲存成功傳回0
  264. }
  265. }
  266. #endregion
  267. #region SecurityImg 產生驗證碼
  268. public void SecurityImg(HttpContext c)
  269. {
  270. var txt = c.Response;
  271. try
  272. {
  273. var flag = string.IsNullOrEmpty(c.Request["flag"]) ? "" : c.Request["flag"].ToString();
  274. var swidth = string.IsNullOrEmpty(c.Request["w"]) ? default_w : c.Request["w"].ToString();
  275. var sheight = string.IsNullOrEmpty(c.Request["h"]) ? default_h : c.Request["h"].ToString();
  276. c.Response.Expires = -1;
  277. parseOk = int.TryParse(swidth, out iwidth);
  278. if (!parseOk)
  279. {
  280. iwidth = Convert.ToInt16(default_w);
  281. }
  282. parseOk = int.TryParse(sheight, out iheight);
  283. if (!parseOk)
  284. {
  285. iheight = Convert.ToInt16(default_h);
  286. }
  287. switch (flag)
  288. {
  289. case "cap1":
  290. case "cap2":
  291. case "cap3":
  292. case "cap4":
  293. captcha_recon(c, iwidth, iheight, flag);
  294. break;
  295. case "cap11":
  296. captchaImg_sum(c, iwidth, iheight, flag);
  297. break;
  298. default:
  299. break;
  300. }
  301. }
  302. catch (Exception ex)
  303. {
  304. LogService.mo_Log.Error("Controller.SecurityImg Error Message:" + ex.Message);
  305. }
  306. }
  307. #endregion
  308. void captchaImg_sum(HttpContext context, int w, int h, string flag)
  309. {
  310. captchaGen(context, flag);
  311. var bmpOut = new Bitmap(w, h);
  312. var g = Graphics.FromImage(bmpOut);
  313. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  314. var x = 0;
  315. g.FillRectangle(Brushes.Black, x, 0, w, h);
  316. float fontsize = 6;
  317. var sizeSetupCompleted = false;
  318. var text = Convert.ToString(context.Session["imgText"]);
  319. while (!sizeSetupCompleted)
  320. {
  321. var mySize = g.MeasureString(text, new Font("Verdana", fontsize, FontStyle.Bold));
  322. if (mySize.Width < w || mySize.Height < h)
  323. {
  324. fontsize += float.Parse("0.1");
  325. }
  326. else
  327. {
  328. sizeSetupCompleted = true;
  329. }
  330. }
  331. for (var i = 0; i < text.Length; i++)
  332. {
  333. if (i.ToString() == context.Session["no1"].ToString() || i.ToString() == context.Session["no2"].ToString())
  334. {
  335. g.DrawString(text.Substring(i, 1), new Font("Verdana", fontsize), new SolidBrush(Color.Red), x, 0);
  336. }
  337. else
  338. {
  339. g.DrawString(text.Substring(i, 1), new Font("Verdana", fontsize), new SolidBrush(Color.White), x, 0);
  340. }
  341. x += Convert.ToInt32(fontsize / 2);
  342. }
  343. var ms = new MemoryStream();
  344. bmpOut.Save(ms, ImageFormat.Png);
  345. var bmpBytes = ms.GetBuffer();
  346. bmpOut.Dispose();
  347. ms.Close();
  348. context.Response.BinaryWrite(bmpBytes);
  349. HttpContext.Current.ApplicationInstance.CompleteRequest();
  350. //context.Response.End();
  351. }
  352. void captcha_recon(HttpContext context, int w, int h, string flag)
  353. {
  354. // Create a random code and store it in the Session object.
  355. var sRandomCode = SecurityUtil.GetRandomNumber(4);
  356. context.Session[BLWording.CAPTCHA + flag] = sRandomCode;
  357. // Create a CAPTCHA image using the text stored in the Session object.
  358. var ci = new RandomImage(sRandomCode, w, h);
  359. // Change the response headers to output a JPEG image.
  360. context.Response.Clear();
  361. context.Response.ContentType = "image/jpeg";
  362. var ms = new MemoryStream();
  363. ci.Image.Save(ms, ImageFormat.Jpeg);
  364. var bmpBytes = ms.GetBuffer();
  365. ci.Dispose();
  366. ms.Close();
  367. context.Response.BinaryWrite(bmpBytes);
  368. HttpContext.Current.ApplicationInstance.CompleteRequest();
  369. //context.Response.End();
  370. }
  371. void captchaGen(HttpContext context, string flag)
  372. {
  373. var ran = new Random();
  374. var no = "";
  375. while (no.Length < 6)
  376. {
  377. no = ran.Next(100000, 1000000).ToString();
  378. }
  379. context.Session["no1"] = ran.Next(5);
  380. context.Session["no2"] = ran.Next(5);
  381. while (context.Session["no1"].ToString() == context.Session["no2"].ToString())
  382. {
  383. context.Session["no2"] = ran.Next(5);
  384. }
  385. context.Session["imgText"] = no;
  386. context.Session[BLWording.CAPTCHA + flag] = int.Parse(no.Substring(int.Parse(context.Session["no1"].ToString()), 1)) + int.Parse(no.Substring(int.Parse(context.Session["no2"].ToString()), 1));
  387. }
  388. public class RandomImage
  389. {
  390. //Default Constructor
  391. public RandomImage() { }
  392. //property
  393. public string Text
  394. {
  395. get { return this.text; }
  396. }
  397. public Bitmap Image
  398. {
  399. get { return this.image; }
  400. }
  401. public int Width
  402. {
  403. get { return this.width; }
  404. }
  405. public int Height
  406. {
  407. get { return this.height; }
  408. }
  409. //Private variable
  410. private string text;
  411. private int width;
  412. private int height;
  413. private Bitmap image;
  414. private Random random = new Random();
  415. //Methods declaration
  416. public RandomImage(string s, int width, int height)
  417. {
  418. this.text = s;
  419. this.SetDimensions(width, height);
  420. this.GenerateImage();
  421. }
  422. public void Dispose()
  423. {
  424. GC.SuppressFinalize(this);
  425. this.Dispose(true);
  426. }
  427. protected virtual void Dispose(bool disposing)
  428. {
  429. if (disposing)
  430. this.image.Dispose();
  431. }
  432. private void SetDimensions(int width, int height)
  433. {
  434. if (width <= 0)
  435. throw new ArgumentOutOfRangeException("width", width,
  436. "Argument out of range, must be greater than zero.");
  437. if (height <= 0)
  438. throw new ArgumentOutOfRangeException("height", height,
  439. "Argument out of range, must be greater than zero.");
  440. this.width = width;
  441. this.height = height;
  442. }
  443. private void GenerateImage()
  444. {
  445. var bitmap = new Bitmap
  446. (this.width, this.height, PixelFormat.Format32bppArgb);
  447. var g = Graphics.FromImage(bitmap);
  448. g.SmoothingMode = SmoothingMode.AntiAlias;
  449. var rect = new Rectangle(0, 0, this.width, this.height);
  450. var hatchBrush = new HatchBrush(HatchStyle.SmallConfetti,
  451. Color.LightGray, Color.White);
  452. g.FillRectangle(hatchBrush, rect);
  453. //SizeF size;
  454. float fontSize = rect.Height + 1;
  455. Font font;
  456. float fontsize = 6;
  457. var sizeSetupCompleted = false;
  458. var text = this.text;
  459. while (!sizeSetupCompleted)
  460. {
  461. var mySize = g.MeasureString(text, new Font("Verdana", fontsize, FontStyle.Bold));
  462. if (mySize.Width < rect.Width || mySize.Height < rect.Height)
  463. {
  464. fontsize += float.Parse("0.1");
  465. }
  466. else
  467. {
  468. sizeSetupCompleted = true;
  469. }
  470. }
  471. font = new Font(FontFamily.GenericSansSerif, fontsize, FontStyle.Bold);
  472. using (var format = new StringFormat())
  473. {
  474. format.Alignment = StringAlignment.Center;
  475. format.LineAlignment = StringAlignment.Center;
  476. var path = new GraphicsPath();
  477. //path.AddString(this.text, font.FontFamily, (int) font.Style,
  478. // font.Size, rect, format);
  479. path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format);
  480. var v = 4F;
  481. PointF[] points =
  482. {
  483. new PointF(this.random.Next(rect.Width) / v, this.random.Next(
  484. rect.Height) / v),
  485. new PointF(rect.Width - this.random.Next(rect.Width) / v,
  486. this.random.Next(rect.Height) / v),
  487. new PointF(this.random.Next(rect.Width) / v,
  488. rect.Height - this.random.Next(rect.Height) / v),
  489. new PointF(rect.Width - this.random.Next(rect.Width) / v,
  490. rect.Height - this.random.Next(rect.Height) / v)
  491. };
  492. var matrix = new Matrix();
  493. matrix.Translate(0F, 0F);
  494. path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
  495. hatchBrush = new HatchBrush(HatchStyle.Percent10, Color.Black, Color.SkyBlue);
  496. var m = Math.Max(rect.Width, rect.Height);
  497. for (var i = 0; i < (int)(rect.Width * rect.Height / 30F); i++)
  498. {
  499. var x = this.random.Next(rect.Width);
  500. var y = this.random.Next(rect.Height);
  501. var w = this.random.Next(m / 50);
  502. var h = this.random.Next(m / 50);
  503. g.FillEllipse(hatchBrush, x, y, w, h);
  504. }
  505. hatchBrush = new HatchBrush(HatchStyle.Percent10, Color.Black, Color.OrangeRed);
  506. g.FillPath(hatchBrush, path);
  507. font.Dispose();
  508. hatchBrush.Dispose();
  509. g.Dispose();
  510. this.image = bitmap;
  511. }
  512. }
  513. }
  514. public bool IsReusable
  515. {
  516. get
  517. {
  518. return false;
  519. }
  520. }
  521. }