/projects/PigeonCms.Core/Modules/PigeonCms.FileUpload/FileUploadControl.cs

http://pigeoncms.googlecode.com/ · C# · 410 lines · 324 code · 54 blank · 32 comment · 22 complexity · d2e1f932aba7e890e5951c19fbcfb270 MD5 · raw file

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using System.Diagnostics;
  11. using System.ComponentModel;
  12. using System.IO;
  13. using System.Collections.Generic;
  14. using System.Threading;
  15. using PigeonCms;
  16. using System.Drawing;
  17. using System.Drawing.Drawing2D;
  18. using System.Drawing.Imaging;
  19. namespace PigeonCms
  20. {
  21. public class FileUploadControl: PigeonCms.BaseModuleControl
  22. {
  23. #region private fields
  24. private string fileExtensions = "";
  25. private int fileSize = 0;
  26. private PigeonCms.FileUploadControl.FileNameTypeEnum fileNameType = PigeonCms.FileUploadControl.FileNameTypeEnum.KeepOriginalName;
  27. private string filePrefix = "";
  28. private string forcedFilename = "";
  29. private string filePath = "~/Public";
  30. private int uploadFields = 1;
  31. private int numOfFilesAllowed = 0;
  32. private int customWidth = 0;
  33. private int customHeight = 0;
  34. private string headerText = "";
  35. private string footerText = "";
  36. private string successText = "";
  37. private string errorText = "";
  38. private string buttonText = "Upload";
  39. private List<string> uploadedFiles = new List<string>();
  40. #endregion
  41. #region events
  42. public delegate void AfterUploadDelegate(/*object sender, EventArgs e*/);
  43. public event AfterUploadDelegate AfterUpload;
  44. #endregion
  45. public enum FileNameTypeEnum
  46. {
  47. KeepOriginalName = 0,
  48. PrefixOriginalName = 1,
  49. PrefixCounter = 2,
  50. ForceFileName = 3
  51. }
  52. #region public fields
  53. /// <summary>
  54. /// allowed file extensions ex. jpg;jpeg;gif
  55. /// </summary>
  56. public string FileExtensions
  57. {
  58. get { return GetStringParam("FileExtensions", fileExtensions).ToLower(); }
  59. set { fileExtensions = value; }
  60. }
  61. public List<string> ExtensionsList
  62. {
  63. get
  64. {
  65. var res = new List<string>();
  66. if (!string.IsNullOrEmpty(this.FileExtensions))
  67. res = Utility.String2List(this.FileExtensions, ';');
  68. return res;
  69. }
  70. }
  71. /// <summary>
  72. /// max size in KB per each file uploaded
  73. /// 0 no limit (web server limit)
  74. /// </summary>
  75. public int FileSize
  76. {
  77. get { return GetIntParam("FileSize", fileSize); }
  78. set { fileSize = value; }
  79. }
  80. public PigeonCms.FileUploadControl.FileNameTypeEnum FileNameType
  81. {
  82. get
  83. {
  84. int res = (int)fileNameType;
  85. res = GetIntParam("FileNameType", res);
  86. return (PigeonCms.FileUploadControl.FileNameTypeEnum)res;
  87. }
  88. set { fileNameType = value; }
  89. }
  90. /// <summary>
  91. /// file prefix
  92. /// </summary>
  93. public string FilePrefix
  94. {
  95. get { return GetStringParam("FilePrefix", filePrefix); }
  96. set { filePrefix = value; }
  97. }
  98. /// <summary>
  99. /// forced file name, only FileTypeEnum.ForceFilename
  100. /// </summary>
  101. public string ForcedFilename
  102. {
  103. get { return GetStringParam("ForcedFilename", forcedFilename); }
  104. set { forcedFilename = value; }
  105. }
  106. /// <summary>
  107. /// where to store the uploaded file
  108. /// </summary>
  109. public string FilePath
  110. {
  111. get
  112. {
  113. string res = "";
  114. res = GetStringParam("FilePath", filePath);
  115. if (!res.EndsWith("/"))
  116. res += "/";
  117. return res;
  118. }
  119. set { filePath = value; }
  120. }
  121. /// <summary>
  122. /// Number of upload fields
  123. /// </summary>
  124. public int UploadFields
  125. {
  126. get { return GetIntParam("UploadFields", uploadFields); }
  127. set { uploadFields = value; }
  128. }
  129. /// <summary>
  130. /// Number of files
  131. /// </summary>
  132. public int NumOfFilesAllowed
  133. {
  134. get { return GetIntParam("NumOfFilesAllowed", numOfFilesAllowed); }
  135. set { numOfFilesAllowed = value; }
  136. }
  137. /// <summary>
  138. /// Resize images to given size
  139. /// </summary>
  140. public int CustomWidth
  141. {
  142. get { return GetIntParam("CustomWidth", customWidth); }
  143. set { customWidth = value; }
  144. }
  145. /// <summary>
  146. /// Resize images to given size
  147. /// </summary>
  148. public int CustomHeight
  149. {
  150. get { return GetIntParam("CustomHeight", customHeight); }
  151. set { customHeight = value; }
  152. }
  153. public string HeaderText
  154. {
  155. get { return GetStringParam("HeaderText", headerText); }
  156. set { headerText = value; }
  157. }
  158. public string FooterText
  159. {
  160. get { return GetStringParam("FooterText", footerText); }
  161. set { footerText = value; }
  162. }
  163. public string SuccessText
  164. {
  165. get { return GetStringParam("SuccessText", successText); }
  166. set { successText = value; }
  167. }
  168. public string ErrorText
  169. {
  170. get { return GetStringParam("ErrorText", errorText); }
  171. set { errorText = value; }
  172. }
  173. public string ButtonText
  174. {
  175. get { return GetStringParam("ButtonText", buttonText); }
  176. set { buttonText = value; }
  177. }
  178. public List<string> UploadedFiles
  179. {
  180. [DebuggerStepThrough()]
  181. get { return uploadedFiles; }
  182. }
  183. #endregion
  184. #region public methods
  185. public void AddField(Panel container, string fieldId)
  186. {
  187. System.Web.UI.WebControls.FileUpload upload =
  188. new System.Web.UI.WebControls.FileUpload();
  189. upload.ID = fieldId;
  190. container.Controls.Add(upload);
  191. Literal litBr = new Literal();
  192. litBr.Text = "<br />";
  193. container.Controls.Add(litBr);
  194. }
  195. public void AddFields(Panel container)
  196. {
  197. for (int i = 0; i < this.UploadFields; i++)
  198. {
  199. AddField(container, "Upload" + i.ToString());
  200. }
  201. }
  202. public bool UploadFile(System.Web.UI.WebControls.FileUpload uploadField, int fileCounter)
  203. {
  204. string fileName = "";
  205. string path = "";
  206. bool res = false;
  207. path = HttpContext.Current.Request.MapPath(this.FilePath);
  208. DirectoryInfo dir = new DirectoryInfo(path);
  209. if (!dir.Exists)
  210. dir.Create();
  211. if (uploadField.HasFile)
  212. {
  213. if (checkExtensions(uploadField.FileName))
  214. {
  215. switch (this.FileNameType)
  216. {
  217. case FileNameTypeEnum.PrefixOriginalName:
  218. fileName = this.FilePrefix + uploadField.FileName;
  219. break;
  220. case FileNameTypeEnum.PrefixCounter:
  221. fileName = this.FilePrefix + fileCounter.ToString() + Path.GetExtension(uploadField.FileName);
  222. break;
  223. case FileNameTypeEnum.ForceFileName:
  224. fileName = this.ForcedFilename + Path.GetExtension(uploadField.FileName);
  225. break;
  226. case FileNameTypeEnum.KeepOriginalName:
  227. default:
  228. fileName = uploadField.FileName;
  229. break;
  230. }
  231. fileName = sanitizeFilename(fileName);
  232. if (checkFileSize(uploadField.PostedFile.ContentLength))
  233. {
  234. saveFile(Path.Combine(path, fileName), uploadField);
  235. res = true;
  236. uploadedFiles.Add(fileName);
  237. }
  238. else
  239. throw new ArgumentException("file too big");
  240. }
  241. else
  242. throw new ArgumentException("file type not allowed");
  243. }
  244. return res;
  245. }
  246. public bool UploadFile(System.Web.UI.WebControls.FileUpload uploadField)
  247. {
  248. return UploadFile(uploadField, 0);
  249. }
  250. public bool UploadFiles(Panel container)
  251. {
  252. bool res = false;
  253. int counter = 0;
  254. uploadedFiles.Clear();
  255. //loop through FileUploads controls in panel
  256. foreach (Control upload in container.Controls)
  257. {
  258. if (upload is System.Web.UI.WebControls.FileUpload)
  259. {
  260. UploadFile((System.Web.UI.WebControls.FileUpload)upload, counter);
  261. counter++;
  262. res = true;
  263. }
  264. }
  265. if (this.AfterUpload != null)
  266. {
  267. this.AfterUpload();
  268. }
  269. return res;
  270. }
  271. #endregion
  272. #region private methods
  273. private bool checkExtensions(string fileName)
  274. {
  275. bool res = true;
  276. string fileExt = Utility.GetFileExt(fileName);
  277. if (this.ExtensionsList.Count > 0)
  278. {
  279. res = this.ExtensionsList.Contains(fileExt.ToLower());
  280. }
  281. return res;
  282. }
  283. private bool checkFileSize(int postedFileSize)
  284. {
  285. bool res = true;
  286. if (this.FileSize > 0)
  287. {
  288. if (postedFileSize > this.FileSize * 1024)
  289. res = false;
  290. }
  291. else if (this.FileSize < 0)
  292. {
  293. res = false;
  294. }
  295. return res;
  296. }
  297. private void saveFile(string filename, FileUpload clientFile)
  298. {
  299. switch (Utility.GetFileExt(filename).ToLower())
  300. {
  301. case "jpg":
  302. case "png":
  303. case "gif":
  304. saveImageFile(new Bitmap(clientFile.PostedFile.InputStream), filename);
  305. break;
  306. default:
  307. clientFile.SaveAs(filename);
  308. break;
  309. }
  310. if (this.CustomWidth > 0)
  311. {
  312. }
  313. }
  314. private void saveImageFile(Bitmap sourceImage, string filename)
  315. {
  316. //see http://www.nerdymusings.com/LPMArticle.asp?ID=32 for jit resize of images
  317. if (this.CustomWidth > 0 && sourceImage.Width > this.CustomWidth)
  318. {
  319. int newImageHeight = (int)(sourceImage.Height * ((float)this.CustomWidth / (float)sourceImage.Width));
  320. Bitmap resizedImage = new Bitmap(this.CustomWidth, newImageHeight);
  321. Graphics gr = Graphics.FromImage(resizedImage);
  322. gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
  323. gr.DrawImage(sourceImage, 0, 0, this.CustomWidth, newImageHeight);
  324. // Save the resized image:
  325. resizedImage.Save(filename, fileExtensionToImageFormat(filename));
  326. }
  327. else
  328. {
  329. // Save the source image (no resizing necessary):
  330. sourceImage.Save(filename, fileExtensionToImageFormat(filename));
  331. }
  332. }
  333. private static ImageFormat fileExtensionToImageFormat(String filePath)
  334. {
  335. String ext = Utility.GetFileExt(filePath).ToLower();
  336. ImageFormat result = ImageFormat.Jpeg;
  337. switch (ext)
  338. {
  339. case "gif":
  340. result = ImageFormat.Gif;
  341. break;
  342. case "png":
  343. result = ImageFormat.Png;
  344. break;
  345. }
  346. return result;
  347. }
  348. private string sanitizeFilename(string fileName)
  349. {
  350. string res = fileName;
  351. res = fileName.Replace(",", "-").Replace(" ", "-");
  352. return res;
  353. }
  354. #endregion
  355. }
  356. }