PageRenderTime 48ms CodeModel.GetById 17ms app.highlight 24ms RepoModel.GetById 1ms app.codeStats 0ms

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