mvc自定义上传控件错误异常提示

Many times, we required to upload file with strongly-typed view and also apply validation on uploading file using data annotation validators. In this article, I would like to share, how can we upload a file and validate that file, firstly at client side and after that at server side.

How to do it..

Step 1 : Designing model with data annotation validation

  
  
  
  
  1. public class RegistrationModel
  2. {
  3. [Required(ErrorMessage = "Please Enter Your Full Name")]
  4. [Display(Name = "Full Name")]
  5. public string Name { get; set; }
  6. [Required(ErrorMessage = "Please Enter Address")]
  7. [Display(Name = "Address")]
  8. [MaxLength(200)]
  9. public string Address { get; set; }
  10. [Required(ErrorMessage = "Please Upload File")]
  11. [Display(Name = "Upload File")]
  12. [ValidateFile]
  13. public HttpPostedFileBase file { get; set; }
  14. }
  15.  
  16. //Customized data annotation validator for uploading file
  17. public class ValidateFileAttribute : ValidationAttribute
  18. {
  19. public override bool IsValid(object value)
  20. {
  21. int MaxContentLength = 1024 * 1024 * 3; //3 MB
  22. string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
  23. var file = value as HttpPostedFileBase;
  24. if (file == null)
  25. return false;
  26. else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
  27. {
  28. ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
  29. return false;
  30. }
  31. else if (file.ContentLength > MaxContentLength)
  32. {
  33. ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
  34. return false;
  35. }
  36. else
  37. return true;
  38. }
  39. }

Step 2 : Designing view based on model

  
  
  
  
  1. <h2>File upload with model validation</h2>
  2. <h3 style="color: green">@ViewBag.Message</h3>
  3.  
  4. @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
  5. {
  6. <fieldset>
  7. <legend></legend>
  8. <ol>
  9. <li>
  10. @Html.LabelFor(m => m.Name)
  11. @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
  12. @Html.ValidationMessageFor(m => m.Name)
  13. </li>
  14. <li>
  15. @Html.LabelFor(m => m.Address)
  16. @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
  17. @Html.ValidationMessageFor(m => m.Address)
  18. </li>
  19. <li class="lifile">
  20. @Html.TextBoxFor(m => m.file, new { type = "file" })
  21. @Html.ValidationMessageFor(m => m.file)
  22. </li>
  23. </ol>
  24. <input type="submit" value="Submit" />
  25. </fieldset>
  26. }

Step 3 : Applying jQuery validation for validating file

  
  
  
  
  1. <script type="text/jscript">
  2. //get file size
  3. function GetFileSize(fileid) {
  4. try {
  5. var fileSize = 0;
  6. //for IE
  7. if ($.browser.msie) {
  8. //before making an object of ActiveXObject,
  9. //please make sure ActiveX is enabled in your IE browser
  10. var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
  11. var objFile = objFSO.getFile(filePath);
  12. var fileSize = objFile.size; //size in kb
  13. fileSize = fileSize / 1048576; //size in mb
  14. }
  15. //for FF, Safari, Opeara and Others
  16. else {
  17. fileSize = $("#" + fileid)[0].files[0].size //size in kb
  18. fileSize = fileSize / 1048576; //size in mb
  19. }
  20. return fileSize;
  21. }
  22. catch (e) {
  23. alert("Error is :" + e);
  24. }
  25. }
  26.  
  27. //get file path from client system
  28. function getNameFromPath(strFilepath) {
  29. var objRE = new RegExp(/([^\/\\]+)$/);
  30. var strName = objRE.exec(strFilepath);
  31. if (strName == null) {
  32. return null;
  33. }
  34. else {
  35. return strName[0];
  36. }
  37. }
  38.  
  39. $(function () {
  40. $("#file").change(function () {
  41. var file = getNameFromPath($(this).val());
  42. if (file != null) {
  43. var extension = file.substr((file.lastIndexOf('.') + 1));
  44. switch (extension) {
  45. case 'jpg':
  46. case 'png':
  47. case 'gif':
  48. case 'pdf':
  49. flag = true;
  50. break;
  51. default:
  52. flag = false;
  53. }
  54. }
  55. if (flag == false) {
  56. $(".lifile > span").text("You can upload only jpg,png,gif,pdf extension file");
  57. return false;
  58. }
  59. else {
  60. var size = GetFileSize('file');
  61. if (size > 3) {
  62. $(".lifile > span").text("You can upload file up to 3 MB");
  63. }
  64. else {
  65. $(".lifile > span").text("");
  66. }
  67. }
  68. });
  69. });
  70. </script>

Step 4 : Designing Controller

  
  
  
  
  1. public ActionResult FileUpload()
  2. {
  3. return View();
  4. }
  5.  
  6. [HttpPost]
  7. public ActionResult FileUpload(RegistrationModel mRegister)
  8. {
  9. //Check server side validation using data annotation
  10. if (ModelState.IsValid)
  11. {
  12. //TO:DO
  13. var fileName = Path.GetFileName(mRegister.file.FileName);
  14. var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
  15. mRegister.file.SaveAs(path);
  16. ViewBag.Message = "File has been uploaded successfully";
  17. ModelState.Clear();
  18. }
  19. return View();
  20. }

How it works...

    mvc自定义上传控件错误异常提示_第1张图片

你可能感兴趣的:(mvc自定义上传控件错误异常提示)