Validate photo file upload


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public void ValidatePhotoUpload(object sender, ServerValidateEventArgs e)
  2. {
  3. string filename = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto")).FileName;
  4. CustomValidator validator = ((CustomValidator)sender);
  5.  
  6. //if file wasn't uploaded at all, exit.
  7. if (filename.Length == 0) return;
  8.  
  9. //make sure the file uploaded is of an accepted type
  10. if (!ValidFileType(filename))
  11. {
  12. e.IsValid = false;
  13. string errorMessage = "Only the following filetypes are accepted: ";
  14.  
  15. foreach (string extension in ValidFileExtensions)
  16. {
  17. errorMessage += extension + " ";
  18. }
  19.  
  20. validator.ErrorMessage = errorMessage;
  21. return;
  22. }
  23.  
  24. //make sure the file is under the size limit
  25. int filesizeInBytes = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto")).PostedFile.ContentLength;
  26. const int maxFileSizeInMB = 4;
  27. const int maxFileSizeInBytes = maxFileSizeInMB * 1000000;
  28. if (filesizeInBytes > maxFileSizeInBytes)
  29. {
  30. e.IsValid = false;
  31. validator.ErrorMessage = "The max file size for uploaded files is " + maxFileSizeInMB + "MB.";
  32. return;
  33. }
  34.  
  35. //make sure a file doesn't already exist on the server with the same name
  36. int numFilesWithSameName = (from f in db.TeamMembers
  37. where f.Photo == filename
  38. select f).Count();
  39. if (numFilesWithSameName > 0)
  40. {
  41. validator.ErrorMessage = "A file already exists with the name " + filename + ". Please rename the file and upload it again.";
  42. e.IsValid = false;
  43. return;
  44. }
  45.  
  46. //validate photo aspect ratio is 8x10 for consistency
  47. System.Drawing.Image file = System.Drawing.Image.FromStream(fuPhoto.PostedFile.InputStream);
  48. float aspectRatio = ((float)file.Height / file.Width);
  49. if (aspectRatio != 1.25)
  50. {
  51. validator.ErrorMessage = "For consistency, team member photos should be a head shot with an aspect ratio of 8x10. For example, if you upload an image that is 1000 pixels tall, it must be 800 pixels wide. Please crop the image to 8x10 and reupload.";
  52. e.IsValid = false;
  53. return;
  54. }
  55.  
  56. //validate photo meets minimum dimsension requirements
  57. if (file.Width < MemberPhotoWidth || file.Height < MemberPhotoHeight)
  58. {
  59. validator.ErrorMessage = "The photo must be at least " + MemberPhotoHeight + " pixels tall and " + MemberPhotoWidth + " pixels wide.";
  60. e.IsValid = false;
  61. return;
  62. }
  63.  
  64. e.IsValid = true;
  65. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.