Nessuna descrizione

ImageUpload.cs 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. using System;
  2. using System.IO;
  3. using System.Web;
  4. using System.Web.UI.HtmlControls;
  5. using System.Drawing;
  6. namespace CallCenter.Utility
  7. {
  8. /// <summary>
  9. /// 文件类型
  10. /// </summary>
  11. public enum FileExtension
  12. {
  13. JPG = 255216,
  14. GIF = 7173,
  15. BMP = 6677,
  16. PNG = 13780,
  17. RAR = 8297,
  18. jpg = 255216,
  19. exe = 7790,
  20. xml = 6063,
  21. html = 6033,
  22. aspx = 239187,
  23. cs = 117115,
  24. js = 119105,
  25. txt = 210187,
  26. sql = 255254
  27. }
  28. /// <summary>
  29. /// 图片检测类
  30. /// </summary>
  31. public static class FileValidation
  32. {
  33. #region 上传图片检测类
  34. /// <summary>
  35. /// 是否允许
  36. /// </summary>
  37. public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx)
  38. {
  39. int fileLen = oFile.ContentLength;
  40. byte[] imgArray = new byte[fileLen];
  41. oFile.InputStream.Read(imgArray, 0, fileLen);
  42. MemoryStream ms = new MemoryStream(imgArray);
  43. System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
  44. string fileclass = "";
  45. byte buffer;
  46. try
  47. {
  48. buffer = br.ReadByte();
  49. fileclass = buffer.ToString();
  50. buffer = br.ReadByte();
  51. fileclass += buffer.ToString();
  52. }
  53. catch { }
  54. br.Close();
  55. ms.Close();
  56. foreach (FileExtension fe in fileEx)
  57. {
  58. if (Int32.Parse(fileclass) == (int)fe) return true;
  59. }
  60. return false;
  61. }
  62. /// <summary>
  63. /// 上传前的图片是否可靠
  64. /// </summary>
  65. public static bool IsSecureUploadPhoto(HttpPostedFile oFile)
  66. {
  67. bool isPhoto = false;
  68. string fileExtension = System.IO.Path.GetExtension(oFile.FileName).ToLower();
  69. string[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
  70. for (int i = 0; i < allowedExtensions.Length; i++)
  71. {
  72. if (fileExtension == allowedExtensions[i])
  73. {
  74. isPhoto = true;
  75. break;
  76. }
  77. }
  78. if (!isPhoto)
  79. {
  80. return true;
  81. }
  82. FileExtension[] fe = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };
  83. if (IsAllowedExtension(oFile, fe))
  84. return true;
  85. else
  86. return false;
  87. }
  88. /// <summary>
  89. /// 上传后的图片是否安全
  90. /// </summary>
  91. /// <param name="photoFile">物理地址</param>
  92. public static bool IsSecureUpfilePhoto(string photoFile)
  93. {
  94. bool isPhoto = false;
  95. string Img = "Yes";
  96. string fileExtension = System.IO.Path.GetExtension(photoFile).ToLower();
  97. string[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
  98. for (int i = 0; i < allowedExtensions.Length; i++)
  99. {
  100. if (fileExtension == allowedExtensions[i])
  101. {
  102. isPhoto = true;
  103. break;
  104. }
  105. }
  106. if (!isPhoto)
  107. {
  108. return true;
  109. }
  110. StreamReader sr = new StreamReader(photoFile, System.Text.Encoding.Default);
  111. string strContent = sr.ReadToEnd();
  112. sr.Close();
  113. string str = "request|<script|.getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language=";
  114. foreach (string s in str.Split('|'))
  115. {
  116. if (strContent.ToLower().IndexOf(s) != -1)
  117. {
  118. File.Delete(photoFile);
  119. Img = "No";
  120. break;
  121. }
  122. }
  123. return (Img == "Yes");
  124. }
  125. #endregion
  126. }
  127. /// <summary>
  128. /// 图片上传类
  129. /// </summary>
  130. //----------------调用-------------------
  131. //imageUpload iu = new imageUpload();
  132. //iu.AddText = "";
  133. //iu.CopyIamgePath = "";
  134. //iu.DrawString_x = ;
  135. //iu.DrawString_y = ;
  136. //iu.DrawStyle = ;
  137. //iu.Font = "";
  138. //iu.FontSize = ;
  139. //iu.FormFile = File1;
  140. //iu.IsCreateImg =;
  141. //iu.IsDraw = ;
  142. //iu.OutFileName = "";
  143. //iu.OutThumbFileName = "";
  144. //iu.SavePath = @"~/image/";
  145. //iu.SaveType = ;
  146. //iu.sHeight = ;
  147. //iu.sWidth = ;
  148. //iu.Upload();
  149. //--------------------------------------
  150. public class ImageUpload
  151. {
  152. #region 私有成员
  153. private int _Error = 0;//返回上传状态。
  154. private int _MaxSize = 20 * 1024 * 1024;//最大单个上传文件 (默认)
  155. private string _FileType = "jpg;gif;bmp;png";//所支持的上传类型用"/"隔开
  156. private string _SavePath = System.Web.HttpContext.Current.Server.MapPath(".") + "\\";//保存文件的实际路径
  157. private int _SaveType = 0;//上传文件的类型,0代表自动生成文件名
  158. private HtmlInputFile _FormFile;//上传控件。
  159. private string _DataUrl;//base64编码的文本
  160. private string _InFileName = "";//非自动生成文件名设置。
  161. private string _OutFileName = "";//输出文件名。
  162. private bool _IsCreateImg = true;//是否生成缩略图。
  163. private bool _Iss = false;//是否有缩略图生成.
  164. private int _Height = 0;//获取上传图片的高度
  165. private int _Width = 0;//获取上传图片的宽度
  166. private int _sHeight = 120;//设置生成缩略图的高度
  167. private int _sWidth = 120;//设置生成缩略图的宽度
  168. private bool _IsDraw = false;//设置是否加水印
  169. private int _DrawStyle = 0;//设置加水印的方式0:文字水印模式,1:图片水印模式,2:不加
  170. private int _DrawString_x = 10;//绘制文本的X坐标(左上角)
  171. private int _DrawString_y = 10;//绘制文本的Y坐标(左上角)
  172. private string _AddText = "GlobalNatureCrafts";//设置水印内容
  173. private string _Font = "宋体";//设置水印字体
  174. private int _FontSize = 12;//设置水印字大小
  175. private int _FileSize = 0;//获取已经上传文件的大小
  176. private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//图片水印模式下的覆盖图片的实际地址
  177. #endregion
  178. #region 公有属性
  179. /// <summary>
  180. /// Error返回值
  181. /// 1、没有上传的文件
  182. /// 2、类型不允许
  183. /// 3、大小超限
  184. /// 4、未知错误
  185. /// 0、上传成功。
  186. /// </summary>
  187. public int Error
  188. {
  189. get { return _Error; }
  190. }
  191. /// <summary>
  192. /// 最大单个上传文件
  193. /// </summary>
  194. public int MaxSize
  195. {
  196. set { _MaxSize = value; }
  197. }
  198. /// <summary>
  199. /// 所支持的上传类型用";"隔开
  200. /// </summary>
  201. public string FileType
  202. {
  203. set { _FileType = value; }
  204. }
  205. /// <summary>
  206. /// 保存文件的实际路径
  207. /// </summary>
  208. public string SavePath
  209. {
  210. set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
  211. get { return _SavePath; }
  212. }
  213. /// <summary>
  214. /// 上传文件的类型,0代表自动生成文件名
  215. /// </summary>
  216. public int SaveType
  217. {
  218. set { _SaveType = value; }
  219. }
  220. /// <summary>
  221. /// 上传控件
  222. /// </summary>
  223. public HtmlInputFile FormFile
  224. {
  225. set { _FormFile = value; }
  226. }
  227. /// <summary>
  228. /// base64编码的文本
  229. /// </summary>
  230. public string DataUrl
  231. {
  232. set { _DataUrl = value; }
  233. }
  234. /// <summary>
  235. /// 非自动生成文件名设置。
  236. /// </summary>
  237. public string InFileName
  238. {
  239. set { _InFileName = value; }
  240. }
  241. /// <summary>
  242. /// 输出文件名
  243. /// </summary>
  244. public string OutFileName
  245. {
  246. get { return _OutFileName; }
  247. set { _OutFileName = value; }
  248. }
  249. /// <summary>
  250. /// 输出的缩略图文件名
  251. /// </summary>
  252. public string OutThumbFileName
  253. {
  254. get;
  255. set;
  256. }
  257. /// <summary>
  258. /// 是否有缩略图生成.
  259. /// </summary>
  260. public bool Iss
  261. {
  262. get { return _Iss; }
  263. }
  264. /// <summary>
  265. /// 获取上传图片的宽度
  266. /// </summary>
  267. public int Width
  268. {
  269. get { return _Width; }
  270. }
  271. /// <summary>
  272. /// 获取上传图片的高度
  273. /// </summary>
  274. public int Height
  275. {
  276. get { return _Height; }
  277. }
  278. /// <summary>
  279. /// 设置缩略图的宽度
  280. /// </summary>
  281. public int sWidth
  282. {
  283. get { return _sWidth; }
  284. set { _sWidth = value; }
  285. }
  286. /// <summary>
  287. /// 设置缩略图的高度
  288. /// </summary>
  289. public int sHeight
  290. {
  291. get { return _sHeight; }
  292. set { _sHeight = value; }
  293. }
  294. /// <summary>
  295. /// 是否生成缩略图
  296. /// </summary>
  297. public bool IsCreateImg
  298. {
  299. get { return _IsCreateImg; }
  300. set { _IsCreateImg = value; }
  301. }
  302. /// <summary>
  303. /// 是否加水印
  304. /// </summary>
  305. public bool IsDraw
  306. {
  307. get { return _IsDraw; }
  308. set { _IsDraw = value; }
  309. }
  310. /// <summary>
  311. /// 设置加水印的方式
  312. /// 0:文字水印模式
  313. /// 1:图片水印模式
  314. /// 2:不加
  315. /// </summary>
  316. public int DrawStyle
  317. {
  318. get { return _DrawStyle; }
  319. set { _DrawStyle = value; }
  320. }
  321. /// <summary>
  322. /// 绘制文本的X坐标(左上角)
  323. /// </summary>
  324. public int DrawString_x
  325. {
  326. get { return _DrawString_x; }
  327. set { _DrawString_x = value; }
  328. }
  329. /// <summary>
  330. /// 绘制文本的Y坐标(左上角)
  331. /// </summary>
  332. public int DrawString_y
  333. {
  334. get { return _DrawString_y; }
  335. set { _DrawString_y = value; }
  336. }
  337. /// <summary>
  338. /// 设置文字水印内容
  339. /// </summary>
  340. public string AddText
  341. {
  342. get { return _AddText; }
  343. set { _AddText = value; }
  344. }
  345. /// <summary>
  346. /// 设置文字水印字体
  347. /// </summary>
  348. public string Font
  349. {
  350. get { return _Font; }
  351. set { _Font = value; }
  352. }
  353. /// <summary>
  354. /// 设置文字水印字的大小
  355. /// </summary>
  356. public int FontSize
  357. {
  358. get { return _FontSize; }
  359. set { _FontSize = value; }
  360. }
  361. /// <summary>
  362. /// 文件大小
  363. /// </summary>
  364. public int FileSize
  365. {
  366. get { return _FileSize; }
  367. set { _FileSize = value; }
  368. }
  369. /// <summary>
  370. /// 图片水印模式下的覆盖图片的实际地址
  371. /// </summary>
  372. public string CopyIamgePath
  373. {
  374. set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
  375. }
  376. public HttpPostedFile PostFile { get; set; }
  377. #endregion
  378. #region 私有方法
  379. /// <summary>
  380. /// 获取文件的后缀名
  381. /// </summary>
  382. private string GetExt(string path)
  383. {
  384. return Path.GetExtension(path);
  385. }
  386. /// <summary>
  387. /// 获取输出文件的文件名
  388. /// </summary>
  389. private string FileName(string Ext)
  390. {
  391. if (_SaveType == 0 || _InFileName.Trim() == "")
  392. return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
  393. else
  394. return _InFileName;
  395. }
  396. /// <summary>
  397. /// 检查上传的文件的类型,是否允许上传。
  398. /// </summary>
  399. private bool IsUpload(string Ext)
  400. {
  401. Ext = Ext.Replace(".", "");
  402. bool b = false;
  403. string[] arrFileType = _FileType.Split(';');
  404. foreach (string str in arrFileType)
  405. {
  406. if (str.ToLower() == Ext.ToLower())
  407. {
  408. b = true;
  409. break;
  410. }
  411. }
  412. return b;
  413. }
  414. #endregion
  415. #region 上传图片
  416. public void Upload()
  417. {
  418. HttpPostedFile hpFile = PostFile;
  419. if (hpFile == null || hpFile.FileName.Trim() == "")
  420. {
  421. _Error = 1;
  422. return;
  423. }
  424. string Ext = GetExt(hpFile.FileName);
  425. if (!IsUpload(Ext))
  426. {
  427. _Error = 2;
  428. return;
  429. }
  430. int iLen = hpFile.ContentLength;
  431. if (iLen > _MaxSize)
  432. {
  433. _Error = 3;
  434. return;
  435. }
  436. try
  437. {
  438. if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
  439. byte[] bData = new byte[iLen];
  440. hpFile.InputStream.Read(bData, 0, iLen);
  441. string FName;
  442. FName = FileName(Ext);
  443. string TempFile = "";
  444. if (_IsDraw)
  445. {
  446. TempFile = FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
  447. }
  448. else
  449. {
  450. TempFile = FName;
  451. }
  452. FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
  453. newFile.Write(bData, 0, bData.Length);
  454. newFile.Flush();
  455. int _FileSizeTemp = hpFile.ContentLength;
  456. string ImageFilePath = _SavePath + FName;
  457. if (_IsDraw)
  458. {
  459. if (_DrawStyle == 0)
  460. {
  461. System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
  462. Graphics g = Graphics.FromImage(Img1);
  463. g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
  464. Font f = new Font(_Font, _FontSize);
  465. Brush b = new SolidBrush(Color.Red);
  466. string addtext = _AddText;
  467. g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
  468. g.Dispose();
  469. Img1.Save(ImageFilePath);
  470. Img1.Dispose();
  471. }
  472. else
  473. {
  474. System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
  475. System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
  476. Graphics g = Graphics.FromImage(image);
  477. g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
  478. g.Dispose();
  479. image.Save(ImageFilePath);
  480. image.Dispose();
  481. }
  482. }
  483. //获取图片的高度和宽度
  484. System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
  485. _Width = Img.Width;
  486. _Height = Img.Height;
  487. //生成缩略图部分
  488. if (_IsCreateImg)
  489. {
  490. #region 缩略图大小只设置了最大范围,并不是实际大小
  491. float realbili = (float)_Width / (float)_Height;
  492. float wishbili = (float)_sWidth / (float)_sHeight;
  493. //实际图比缩略图最大尺寸更宽矮,以宽为准
  494. if (realbili > wishbili)
  495. {
  496. _sHeight = (int)((float)_sWidth / realbili);
  497. }
  498. //实际图比缩略图最大尺寸更高长,以高为准
  499. else
  500. {
  501. _sWidth = (int)((float)_sHeight * realbili);
  502. }
  503. #endregion
  504. this.OutThumbFileName = FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString();
  505. string ImgFilePath = _SavePath + this.OutThumbFileName;
  506. System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
  507. newImg.Save(ImgFilePath);
  508. newImg.Dispose();
  509. _Iss = true;
  510. }
  511. if (_IsDraw)
  512. {
  513. if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
  514. {
  515. newFile.Dispose();
  516. File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
  517. }
  518. }
  519. newFile.Close();
  520. newFile.Dispose();
  521. _OutFileName = FName;
  522. _FileSize = _FileSizeTemp;
  523. _Error = 0;
  524. return;
  525. }
  526. catch
  527. {
  528. _Error = 4;
  529. return;
  530. }
  531. }
  532. public void Upload64()
  533. {
  534. int delLength = _DataUrl.IndexOf(',') + 1;
  535. string str = _DataUrl.Substring(delLength, _DataUrl.Length - delLength);
  536. byte[] bData = Convert.FromBase64String(str);
  537. int iLen = bData.Length;
  538. if (iLen > _MaxSize)
  539. {
  540. _Error = 3;
  541. return;
  542. }
  543. try
  544. {
  545. if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
  546. string FName;
  547. FName = FileName(".jpg");
  548. string TempFile = "";
  549. if (_IsDraw)
  550. {
  551. TempFile = FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
  552. }
  553. else
  554. {
  555. TempFile = FName;
  556. }
  557. FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
  558. newFile.Write(bData, 0, bData.Length);
  559. newFile.Flush();
  560. int _FileSizeTemp = iLen;
  561. string ImageFilePath = _SavePath + FName;
  562. if (_IsDraw)
  563. {
  564. if (_DrawStyle == 0)
  565. {
  566. System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
  567. Graphics g = Graphics.FromImage(Img1);
  568. g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
  569. Font f = new Font(_Font, _FontSize);
  570. Brush b = new SolidBrush(Color.Red);
  571. string addtext = _AddText;
  572. g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
  573. g.Dispose();
  574. Img1.Save(ImageFilePath);
  575. Img1.Dispose();
  576. }
  577. else
  578. {
  579. System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
  580. System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
  581. Graphics g = Graphics.FromImage(image);
  582. g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
  583. g.Dispose();
  584. image.Save(ImageFilePath);
  585. image.Dispose();
  586. }
  587. }
  588. //获取图片的高度和宽度
  589. System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
  590. _Width = Img.Width;
  591. _Height = Img.Height;
  592. //生成缩略图部分
  593. if (_IsCreateImg)
  594. {
  595. #region 缩略图大小只设置了最大范围,并不是实际大小
  596. float realbili = (float)_Width / (float)_Height;
  597. float wishbili = (float)_sWidth / (float)_sHeight;
  598. //实际图比缩略图最大尺寸更宽矮,以宽为准
  599. if (realbili > wishbili)
  600. {
  601. _sHeight = (int)((float)_sWidth / realbili);
  602. }
  603. //实际图比缩略图最大尺寸更高长,以高为准
  604. else
  605. {
  606. _sWidth = (int)((float)_sHeight * realbili);
  607. }
  608. #endregion
  609. this.OutThumbFileName = FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString();
  610. string ImgFilePath = _SavePath + this.OutThumbFileName;
  611. System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
  612. newImg.Save(ImgFilePath);
  613. newImg.Dispose();
  614. _Iss = true;
  615. }
  616. if (_IsDraw)
  617. {
  618. if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
  619. {
  620. newFile.Dispose();
  621. File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
  622. }
  623. }
  624. newFile.Close();
  625. newFile.Dispose();
  626. _OutFileName = FName;
  627. _FileSize = _FileSizeTemp;
  628. _Error = 0;
  629. return;
  630. }
  631. catch(Exception E)
  632. {
  633. LogFactory.GetLogger("").Error(E.ToJson());
  634. _Error = 4;
  635. return;
  636. }
  637. }
  638. #endregion
  639. }
  640. }