ImageUpload.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. using System;
  2. using System.IO;
  3. using System.Web;
  4. using System.Web.UI.HtmlControls;
  5. using System.Drawing;
  6. namespace Ant.Service.Utilities
  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 = 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 _InFileName = "";//非自动生成文件名设置。
  160. private string _OutFileName = "";//输出文件名。
  161. private bool _IsCreateImg = true;//是否生成缩略图。
  162. private bool _Iss = false;//是否有缩略图生成.
  163. private int _Height = 0;//获取上传图片的高度
  164. private int _Width = 0;//获取上传图片的宽度
  165. private int _sHeight = 120;//设置生成缩略图的高度
  166. private int _sWidth = 120;//设置生成缩略图的宽度
  167. private bool _IsDraw = false;//设置是否加水印
  168. private int _DrawStyle = 0;//设置加水印的方式0:文字水印模式,1:图片水印模式,2:不加
  169. private int _DrawString_x = 10;//绘制文本的X坐标(左上角)
  170. private int _DrawString_y = 10;//绘制文本的Y坐标(左上角)
  171. private string _AddText = "GlobalNatureCrafts";//设置水印内容
  172. private string _Font = "宋体";//设置水印字体
  173. private int _FontSize = 12;//设置水印字大小
  174. private int _FileSize = 0;//获取已经上传文件的大小
  175. private string _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(".") + "/images/5dm_new.jpg";//图片水印模式下的覆盖图片的实际地址
  176. #endregion
  177. #region 公有属性
  178. /// <summary>
  179. /// Error返回值
  180. /// 1、没有上传的文件
  181. /// 2、类型不允许
  182. /// 3、大小超限
  183. /// 4、未知错误
  184. /// 0、上传成功。
  185. /// </summary>
  186. public int Error
  187. {
  188. get { return _Error; }
  189. }
  190. /// <summary>
  191. /// 最大单个上传文件
  192. /// </summary>
  193. public int MaxSize
  194. {
  195. set { _MaxSize = value; }
  196. }
  197. /// <summary>
  198. /// 所支持的上传类型用";"隔开
  199. /// </summary>
  200. public string FileType
  201. {
  202. set { _FileType = value; }
  203. }
  204. /// <summary>
  205. /// 保存文件的实际路径
  206. /// </summary>
  207. public string SavePath
  208. {
  209. set { _SavePath = System.Web.HttpContext.Current.Server.MapPath(value); }
  210. get { return _SavePath; }
  211. }
  212. /// <summary>
  213. /// 上传文件的类型,0代表自动生成文件名
  214. /// </summary>
  215. public int SaveType
  216. {
  217. set { _SaveType = value; }
  218. }
  219. /// <summary>
  220. /// 上传控件
  221. /// </summary>
  222. public HtmlInputFile FormFile
  223. {
  224. set { _FormFile = value; }
  225. }
  226. /// <summary>
  227. /// 非自动生成文件名设置。
  228. /// </summary>
  229. public string InFileName
  230. {
  231. set { _InFileName = value; }
  232. }
  233. /// <summary>
  234. /// 输出文件名
  235. /// </summary>
  236. public string OutFileName
  237. {
  238. get { return _OutFileName; }
  239. set { _OutFileName = value; }
  240. }
  241. /// <summary>
  242. /// 输出的缩略图文件名
  243. /// </summary>
  244. public string OutThumbFileName
  245. {
  246. get;
  247. set;
  248. }
  249. /// <summary>
  250. /// 是否有缩略图生成.
  251. /// </summary>
  252. public bool Iss
  253. {
  254. get { return _Iss; }
  255. }
  256. /// <summary>
  257. /// 获取上传图片的宽度
  258. /// </summary>
  259. public int Width
  260. {
  261. get { return _Width; }
  262. }
  263. /// <summary>
  264. /// 获取上传图片的高度
  265. /// </summary>
  266. public int Height
  267. {
  268. get { return _Height; }
  269. }
  270. /// <summary>
  271. /// 设置缩略图的宽度
  272. /// </summary>
  273. public int sWidth
  274. {
  275. get { return _sWidth; }
  276. set { _sWidth = value; }
  277. }
  278. /// <summary>
  279. /// 设置缩略图的高度
  280. /// </summary>
  281. public int sHeight
  282. {
  283. get { return _sHeight; }
  284. set { _sHeight = value; }
  285. }
  286. /// <summary>
  287. /// 是否生成缩略图
  288. /// </summary>
  289. public bool IsCreateImg
  290. {
  291. get { return _IsCreateImg; }
  292. set { _IsCreateImg = value; }
  293. }
  294. /// <summary>
  295. /// 是否加水印
  296. /// </summary>
  297. public bool IsDraw
  298. {
  299. get { return _IsDraw; }
  300. set { _IsDraw = value; }
  301. }
  302. /// <summary>
  303. /// 设置加水印的方式
  304. /// 0:文字水印模式
  305. /// 1:图片水印模式
  306. /// 2:不加
  307. /// </summary>
  308. public int DrawStyle
  309. {
  310. get { return _DrawStyle; }
  311. set { _DrawStyle = value; }
  312. }
  313. /// <summary>
  314. /// 绘制文本的X坐标(左上角)
  315. /// </summary>
  316. public int DrawString_x
  317. {
  318. get { return _DrawString_x; }
  319. set { _DrawString_x = value; }
  320. }
  321. /// <summary>
  322. /// 绘制文本的Y坐标(左上角)
  323. /// </summary>
  324. public int DrawString_y
  325. {
  326. get { return _DrawString_y; }
  327. set { _DrawString_y = value; }
  328. }
  329. /// <summary>
  330. /// 设置文字水印内容
  331. /// </summary>
  332. public string AddText
  333. {
  334. get { return _AddText; }
  335. set { _AddText = value; }
  336. }
  337. /// <summary>
  338. /// 设置文字水印字体
  339. /// </summary>
  340. public string Font
  341. {
  342. get { return _Font; }
  343. set { _Font = value; }
  344. }
  345. /// <summary>
  346. /// 设置文字水印字的大小
  347. /// </summary>
  348. public int FontSize
  349. {
  350. get { return _FontSize; }
  351. set { _FontSize = value; }
  352. }
  353. /// <summary>
  354. /// 文件大小
  355. /// </summary>
  356. public int FileSize
  357. {
  358. get { return _FileSize; }
  359. set { _FileSize = value; }
  360. }
  361. /// <summary>
  362. /// 图片水印模式下的覆盖图片的实际地址
  363. /// </summary>
  364. public string CopyIamgePath
  365. {
  366. set { _CopyIamgePath = System.Web.HttpContext.Current.Server.MapPath(value); }
  367. }
  368. #endregion
  369. #region 私有方法
  370. /// <summary>
  371. /// 获取文件的后缀名
  372. /// </summary>
  373. private string GetExt(string path)
  374. {
  375. return Path.GetExtension(path);
  376. }
  377. /// <summary>
  378. /// 获取输出文件的文件名
  379. /// </summary>
  380. private string FileName(string Ext)
  381. {
  382. if (_SaveType == 0 || _InFileName.Trim() == "")
  383. return DateTime.Now.ToString("yyyyMMddHHmmssfff") + Ext;
  384. else
  385. return _InFileName;
  386. }
  387. /// <summary>
  388. /// 检查上传的文件的类型,是否允许上传。
  389. /// </summary>
  390. private bool IsUpload(string Ext)
  391. {
  392. Ext = Ext.Replace(".", "");
  393. bool b = false;
  394. string[] arrFileType = _FileType.Split(';');
  395. foreach (string str in arrFileType)
  396. {
  397. if (str.ToLower() == Ext.ToLower())
  398. {
  399. b = true;
  400. break;
  401. }
  402. }
  403. return b;
  404. }
  405. #endregion
  406. #region 上传图片
  407. public void Upload()
  408. {
  409. HttpPostedFile hpFile = _FormFile.PostedFile;
  410. if (hpFile == null || hpFile.FileName.Trim() == "")
  411. {
  412. _Error = 1;
  413. return;
  414. }
  415. string Ext = GetExt(hpFile.FileName);
  416. if (!IsUpload(Ext))
  417. {
  418. _Error = 2;
  419. return;
  420. }
  421. int iLen = hpFile.ContentLength;
  422. if (iLen > _MaxSize)
  423. {
  424. _Error = 3;
  425. return;
  426. }
  427. try
  428. {
  429. if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
  430. byte[] bData = new byte[iLen];
  431. hpFile.InputStream.Read(bData, 0, iLen);
  432. string FName;
  433. FName = FileName(Ext);
  434. string TempFile = "";
  435. if (_IsDraw)
  436. {
  437. TempFile = FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString();
  438. }
  439. else
  440. {
  441. TempFile = FName;
  442. }
  443. FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create);
  444. newFile.Write(bData, 0, bData.Length);
  445. newFile.Flush();
  446. int _FileSizeTemp = hpFile.ContentLength;
  447. string ImageFilePath = _SavePath + FName;
  448. if (_IsDraw)
  449. {
  450. if (_DrawStyle == 0)
  451. {
  452. System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile);
  453. Graphics g = Graphics.FromImage(Img1);
  454. g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height);
  455. Font f = new Font(_Font, _FontSize);
  456. Brush b = new SolidBrush(Color.Red);
  457. string addtext = _AddText;
  458. g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y);
  459. g.Dispose();
  460. Img1.Save(ImageFilePath);
  461. Img1.Dispose();
  462. }
  463. else
  464. {
  465. System.Drawing.Image image = System.Drawing.Image.FromStream(newFile);
  466. System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath);
  467. Graphics g = Graphics.FromImage(image);
  468. 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);
  469. g.Dispose();
  470. image.Save(ImageFilePath);
  471. image.Dispose();
  472. }
  473. }
  474. //获取图片的高度和宽度
  475. System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile);
  476. _Width = Img.Width;
  477. _Height = Img.Height;
  478. //生成缩略图部分
  479. if (_IsCreateImg)
  480. {
  481. #region 缩略图大小只设置了最大范围,并不是实际大小
  482. float realbili = (float)_Width / (float)_Height;
  483. float wishbili = (float)_sWidth / (float)_sHeight;
  484. //实际图比缩略图最大尺寸更宽矮,以宽为准
  485. if (realbili > wishbili)
  486. {
  487. _sHeight = (int)((float)_sWidth / realbili);
  488. }
  489. //实际图比缩略图最大尺寸更高长,以高为准
  490. else
  491. {
  492. _sWidth = (int)((float)_sHeight * realbili);
  493. }
  494. #endregion
  495. this.OutThumbFileName = FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString();
  496. string ImgFilePath = _SavePath + this.OutThumbFileName;
  497. System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero);
  498. newImg.Save(ImgFilePath);
  499. newImg.Dispose();
  500. _Iss = true;
  501. }
  502. if (_IsDraw)
  503. {
  504. if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()))
  505. {
  506. newFile.Dispose();
  507. File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString());
  508. }
  509. }
  510. newFile.Close();
  511. newFile.Dispose();
  512. _OutFileName = FName;
  513. _FileSize = _FileSizeTemp;
  514. _Error = 0;
  515. return;
  516. }
  517. catch (Exception ex)
  518. {
  519. _Error = 4;
  520. return;
  521. }
  522. }
  523. #endregion
  524. }
  525. }