Introduction

This article shows by example how to upload a file and validate it. We can apply the validation when uploading the file using Data Annotation validators.

The following is the procedure for creating this application.

Step 1

Create the Web API application.

Step 2

In the "HomeController.cs" file add the new "ActionResult" method.

The code of the "HomeController.cs" file is as in the following:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using Upload.Models;
  8. namespace Upload.Controllers
  9. {
  10. public class HomeController : Controller
  11. {
  12. public ActionResult Index()
  13. {
  14. return View();
  15. }
  16. public ActionResult RecordUpload()
  17. {
  18. return View();
  19. }
  20. [HttpPost]
  21. public ActionResult RecordUpload(RModel fregister)
  22. {
  23. if (ModelState.IsValid)
  24. {
  25. var Nameofrecord = Path.GetFileName(fregister.file.FileName);
  26. var sourcepath = Path.Combine(Server.MapPath("~/Content"), Nameofrecord);
  27. fregister.file.SaveAs(sourcepath);
  28. ViewBag.Message = "Your file Uploaded successfully";
  29. ModelState.Clear();
  30. }
  31. return View();
  32. }
  33. }
  34. }

Here the "ActionResult" class encapsulates the action of the "RecordUpload" method and the "HttpPost" attribute represents an attribute that restricts an action method, in other words "RecordUpload".

Step 3

We create a View "RecordUpload.cshtml" as in the following:

Write this code in this view.

  1. @model Upload.Models.RModel
  2. @{
  3. ViewBag.Title = "Upload File using Type Strongly view";
  4. }
  5. <script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
  6. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
  7. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
  8. <script type="text/jscript">
  9. function FindFileSize(fileid) {
  10. try {
  11. var fSize = 0;
  12. if ($.browser.msie) {
  13. var obj = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
  14. var fileo = obj.getFile(filePath);
  15. var fSize = fileo.size;
  16. fSize = fSize / 1048576;
  17. }
  18. else {
  19. fSize = $("#" + fileid)[0].files[0].size
  20. fSize = fSize / 1048576;
  21. }
  22. return fSize;
  23. }
  24. catch (e) {
  25. alert("Error occured :" + e);
  26. }
  27. }
  28. function getNameFromPath(strFilesource) {
  29. var OBJ = new RegExp();
  30. var sName = OBJ.exec(strFilsource);
  31. if (sName == null) {
  32. return null;
  33. }
  34. else {
  35. return sName[0];
  36. }
  37. }
  38. $(function () {
  39. $("#record").change(function () {
  40. var record = getNameFromPath($(this).val());
  41. if (record != null) {
  42. var suffix = file.substr((file.lastIndexOf('.') + 1));
  43. switch (suffix) {
  44. case 'jpg':
  45. case 'png':
  46. case 'gif':
  47. case 'pdf':
  48. flag = true;
  49. break;
  50. default:
  51. flag = false;
  52. }
  53. }
  54. if (flag == false) {
  55. $(".lifile > span").text("Extension of file that can be upload jpg,png,gif,pdf extension file");
  56. return false;
  57. }
  58. else {
  59. var size = GetFileSize('file');
  60. if (size > 3) {
  61. $(".lifile > span").text("The Uploading file Size 3 MB");
  62. }
  63. else {
  64. $(".lifile > span").text("");
  65. }
  66. }
  67. });
  68. });
  69. </script>
  70. <h2>Uploading File using model validation</h2>
  71. <h3 style="color: green">@ViewBag.Message</h3>
  72. @using (Html.BeginForm("RecordUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
  73. {
  74. <fieldset>
  75. <legend></legend>
  76. <ol>
  77. <li>
  78. @Html.LabelFor(l => l.YourName)
  79. @Html.TextBoxFor(l => l.YourName, new { maxlength = 50 })
  80. @Html.ValidationMessageFor(l => l.YourName)
  81. </li>
  82. <li>
  83. @Html.LabelFor(l => l.TypeAddress)
  84. @Html.TextAreaFor(l => l.TypeAddress, new { maxlength = 200 })
  85. @Html.ValidationMessageFor(l => l.TypeAddress)
  86. </li>
  87. <li class="lifile">
  88. @Html.TextBoxFor(l => l.file, new { type = "file" })
  89. @Html.ValidationMessageFor(l => l.file)
  90. </li>
  91. </ol>
  92. <input type="submit" value="Submit" />
  93. </fieldset>
  94. }

Step 4

Create a new model class.

Write this code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Web.Mvc;
  7. using System.Text.RegularExpressions;
  8. namespace Upload.Models
  9. {
  10. public class RModel
  11. {
  12. [Required(ErrorMessage = "Type your Full Name")]
  13. [Display(Name = "YourName")]
  14. public string YourName { get; set; }
  15. [Required(ErrorMessage = "Type Address")]
  16. [Display(Name = "TypeAddress")]
  17. [MaxLength(250)]
  18. public string TypeAddress { get; set; }
  19. [Required(ErrorMessage = "Upload the File")]
  20. [Display(Name = "Upload")]
  21. [ValidateFile]
  22. public HttpPostedFileBase file { get; set; }
  23. }
  24. public class ValidateFileAttribute : ValidationAttribute
  25. {
  26. public override bool IsValid(object value)
  27. {
  28. int MaxContentLength = 1024 * 1024 * 3;
  29. string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
  30. var file = value as HttpPostedFileBase;
  31. if (file == null)
  32. return false;
  33. else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
  34. {
  35. ErrorMessage = "Upload File Photo Type: " + string.Join(", ", AllowedFileExtensions);
  36. return false;
  37. }
  38. else if (file.ContentLength > MaxContentLength)
  39. {
  40. ErrorMessage = "The Size of Photo is too large : " + (MaxContentLength / 1024).ToString() + "MB";
  41. return false;
  42. }
  43. else
  44. return true;
  45. }
  46. }
  47. }

In this code "YourName", "TypeAddress" and "Upload" are required fields. If any are empty then it gives an error message. Here we will provide some

extensions of files that specify what file extensions can be uploaded and defines the maximum size of the files. Files of the specified length and less can uploaded otherwise it gives an error message.

Step 5

Open the _Layout.cshtml file.

Change its code as:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>@ViewBag.Title - ASP.NET WebAPI Application</title>
  6. <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
  7. <meta name="viewport" content="width=device-width" />
  8. @System.Web.Optimization.Styles.Render("~/Content/css")
  9. @System.Web.Optimization.Scripts.Render("~/bundles/modernizr")
  10. </head>
  11. <body>
  12. <header>
  13. <div class="content-wrapper">
  14. <div>
  15. <p class="site-title">@Html.ActionLink("Web API Strongly file Upload", "Illustration", "Home")</p><br />
  16. </div>
  17. <div style=" clear:both">
  18. <nav>
  19. <ul id="menu">
  20. <li>@Html.ActionLink(" Upload File", "RecordUpload", "Home")</li>
  21. </ul>
  22. </nav>
  23. </div>
  24. </div>
  25. </header>
  26. <div id="body">
  27. @RenderSection("featured", required: false)
  28. <section class="content-wrapper main-content clear-fix">
  29. @RenderBody()
  30. </section>
  31. </div>
  32. <footer>
  33. <div class="content-wrapper">
  34. <div class="float-left">
  35. <p>© @DateTime.Now.Year - My ASP.NET WebAPI Application</p>
  36. </div>
  37. </div>
  38. </footer>
  39. @Scripts.Render("~/bundles/jquery")
  40. @RenderSection("scripts", required: false)
  41. </body>
  42. </html>

Step 6

Now execute the application.

val4.jpg

Click on the UploadFile tag.

val5.jpg

Fill in all fields and click on the "Submit" button.

val6.jpg

Now we check the Required field validation. We left one field empty and click on the "Submit" button.

val7.jpg

It displays the error message.

val8.jpg

Then when we upload a different extension file then it again shows the error message.