Please enable Javascript to correctly display the contents on Dot Net Tricks!

File upload with strongly typed view and model validation

  Author : Shailendra Chauhan
Updated On : 23 Nov 2016
Total Views : 151,812   
Support : MVC4 & MVC3
 

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

public class RegistrationModel
{
 [Required(ErrorMessage = "Please Enter Your Full Name")]
 [Display(Name = "Full Name")]
 public string Name { get; set; }
 
 [Required(ErrorMessage = "Please Enter Address")]
 [Display(Name = "Address")]
 [MaxLength(200)]
 public string Address { get; set; }
 
 [Required(ErrorMessage = "Please Upload File")]
 [Display(Name = "Upload File")]
 [ValidateFile]
 public HttpPostedFileBase file { get; set; }
}

//Customized data annotation validator for uploading file
public class ValidateFileAttribute : ValidationAttribute
{
 public override bool IsValid(object value)
 {
 int MaxContentLength = 1024 * 1024 * 3; //3 MB
 string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
 
 var file = value as HttpPostedFileBase;
 
 if (file == null)
 return false;
 else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
 {
 ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
 return false;
 }
 else if (file.ContentLength > MaxContentLength)
 {
 ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
 return false;
 }
 else
 return true;
 }
}

Step 2 : Designing view based on model

<h2>File upload with model validation</h2>
<h3 style="color: green">@ViewBag.Message</h3>

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
 <fieldset>
 <legend></legend>
 <ol>
 <li>
 @Html.LabelFor(m => m.Name)
 @Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
 @Html.ValidationMessageFor(m => m.Name)
 </li>
 <li>
 @Html.LabelFor(m => m.Address)
 @Html.TextAreaFor(m => m.Address, new { maxlength = 200 })
 @Html.ValidationMessageFor(m => m.Address)
 </li>
 <li class="lifile">
 @Html.TextBoxFor(m => m.file, new { type = "file" })
 @Html.ValidationMessageFor(m => m.file)
 </li>
 </ol>
 <input type="submit" value="Submit" />
 </fieldset>
}

Step 3 : Applying jQuery validation for validating file

<script type="text/jscript">
//get file size
function GetFileSize(fileid) {
 try {
 var fileSize = 0;
 //for IE
 if ($.browser.msie) {
 //before making an object of ActiveXObject, 
 //please make sure ActiveX is enabled in your IE browser
 var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
 var objFile = objFSO.getFile(filePath);
 var fileSize = objFile.size; //size in kb
 fileSize = fileSize / 1048576; //size in mb 
 }
 //for FF, Safari, Opeara and Others
 else {
 fileSize = $("#" + fileid)[0].files[0].size //size in kb
 fileSize = fileSize / 1048576; //size in mb 
 }
 
 return fileSize;
 }
 catch (e) {
 alert("Error is :" + e);
 }
}

//get file path from client system
function getNameFromPath(strFilepath) {
 var objRE = new RegExp(/([^\/\\]+)$/);
 var strName = objRE.exec(strFilepath);
 
 if (strName == null) {
 return null;
 }
 else {
 return strName[0];
 }
}

$(function () {
 $("#file").change(function () {
 var file = getNameFromPath($(this).val());
 if (file != null) {
 var extension = file.substr((file.lastIndexOf('.') + 1));
 switch (extension) {
 case 'jpg':
 case 'png':
 case 'gif':
 case 'pdf':
 flag = true;
 break;
 default:
 flag = false;
 }
 }
 if (flag == false) {
 $(".lifile > span").text("You can upload only jpg,png,gif,pdf extension file");
 return false;
 }
 else {
 var size = GetFileSize('file');
 if (size > 3) {
 $(".lifile > span").text("You can upload file up to 3 MB");
 }
 else {
 $(".lifile > span").text("");
 }
 }
 });
});
</script>

Step 4 : Designing Controller

public ActionResult FileUpload()
{
 return View();
}

[HttpPost]
public ActionResult FileUpload(RegistrationModel mRegister)
{
 //Check server side validation using data annotation
 if (ModelState.IsValid)
 {
 //TO:DO
 var fileName = Path.GetFileName(mRegister.file.FileName);
 var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
 mRegister.file.SaveAs(path);
 ViewBag.Message = "File has been uploaded successfully";
 ModelState.Clear();
 }
 return View();
}

How it works...

What do you think?

I hope you will enjoy the tips while working with MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.


ABOUT AUTHOR

Shailendra Chauhan
Author, Architect, Corporate Trainer and Microsoft MVP

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers, ASP.NET MVC Interview Questions and Answers, AngularJS Interview Questions and Answers and LINQ Interview Questions and AnswersKnow more...

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
13 FEB
ASP.NET Core Development (online)

07:00 AM-09:00 AM IST( MON, WED, FRI)

Know More
25 JAN
Angular2 and Angular1 Development (online)

09:00 PM-10:30 PM IST(MON-FRI)

Know More
24 JAN
ASP.NET MVC with Angular2 Development (online)

07:00 AM-09:00 AM IST(Tuesday & Thursday)

Know More
20 JAN
NODEJS & MEAN Stack 2 Development (online)

09:00 PM-11:00 PM IST( MON, WED, FRI)

Know More
15 JAN
PPC Marketing (offline)

04:00 PM-05:300 PM

14 JAN
Xamarin Forms : Build Cross-platform Apps (offline)

05:00 PM-06:30 PM IST

10 JAN
ASP.NET MVC with AngularJS Development (online)

09:00 PM-11:00 PM IST on (TUE, THRU,SAT)

3 JAN
ASP.NET MVC with AngularJS Development (online)

07:00 AM-09:00 AM IST

31 DEC
ASP.NET MVC with AngularJS Development (offline)

09:30 AM-11:00 AM

31 DEC
Angular2 and Angular1 Development (offline)

11:00 AM-12:30 AM

26 NOV
ASP.NET MVC with AngularJS Development (offline)

03:00 PM-04:30 PM

5 NOV
ASP.NET MVC with AngularJS Development (offline)

08:00 AM-09:30 AM

4 SEP
MEAN Stack 2 Development (offline)

11:00 AM-12:30 PM.

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+