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

How to upload a file in ASP.MVC

 Print 
  Author : Shailendra Chauhan
Posted On : 12 Jan 2013
Total Views : 195,484   
Updated On : 06 Jul 2017
 

Uploading a file in Asp.Net MVC application is very easy. The posted file is automatically available as a HttpPostedFileBase parameters in the action of the controller. For uploading a file on the server you required to have a file input control within html form having encoding type set to multipart/form-data. The default encoding type of a form is application/x-www-form-urlencoded and this is no sufficient for posting a large amount of data to server.

How to do it..

Step 1 : Form for uploading the file

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
 @Html.ValidationSummary();
 <ol>
 <li class="lifile">
 <input type="file" id="fileToUpload" name="file" />
 <span class="field-validation-error" id="spanfile"></span>
 </li>
 </ol>
 <input type="submit" id="btnSubmit" value="Upload" />
}

Step 2 : Validating the file on client side

<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];
 }
}

$("#btnSubmit").live("click", function () 
{
 if ($('#fileToUpload').val() == "") 
 {
 $("#spanfile").html("Please upload file");
 return false;
 }
 else 
 {
 return checkfile();
 }
});

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

$(function () 
{
 $("#fileToUpload").change(function () {
 checkfile();});
});
</script>

Step 3 : Controller's action for receiving the posted file

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
 if (ModelState.IsValid)
 {
 if (file == null)
 {
 ModelState.AddModelError("File", "Please Upload Your file");
 }
 else if (file.ContentLength > 0)
 {
 int MaxContentLength = 1024 * 1024 * 3; //3 MB
 string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
 
 if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
 {
 ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
 }
 
 else if (file.ContentLength > MaxContentLength)
 {
 ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
 }
 else
 {
 //TO:DO
 var fileName = Path.GetFileName(file.FileName);
 var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
 file.SaveAs(path);
 ModelState.Clear();
 ViewBag.Message = "File uploaded successfully";
 }
 }
 }
 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...

Free Interview Books
 
COMMENTS
24 SEP
Angular2 and Angular4 (Classroom)
08:30 AM-11:30 AM IST
23 SEP
MEAN Stack (Classroom)
8:30 Am To 11:30 Am
23 SEP
Microsoft Azure Infrastructure Solutions (Online)
08:00 PM-11:00 PM IST / 9:30 AM-12:30 PM CST
20 SEP
MEAN Stack (Online)
07:00 AM-09:00 AM IST
20 SEP
ASP.NET MVC with Angular4 (Online)
9:00PM- 11:00PM IST(+5:30GMT)
16 SEP
Angular2 and Angular4 (Online)
08:00 AM-10:00 AM IST(+5.30 GMT)
7 SEP
ASP.NET MVC with Angular4 (Online)
09:00 PM to 11:00 PM IST (+5:30 GMT)
22 AUG
ASP.NET Core with Angular4 (Online)
07:00 AM - 9:00 AM IST(+5:30 GMT)
19 AUG
MEAN Stack 2 (Online)
5:30 Pm - 7:00 PM IST (+5:30 GMT)
19 AUG
ASP.NET MVC with Angular4 (Online)
10:30 Am to 12:30 PM IST (+ 5:30 GMT)
19 AUG
NodeJS with Angular4 (Classroom)
04:00 PM to 07:00 PM IST (+5:30 GMT)
12 AUG
ASP.NET MVC with Angular4 (Classroom)
11:30 AM - 1:30 PM IST (+5:30GMT)
15 JUL
ASP.NET MVC with Angular4 (Online)
03:30 PM - 05:30 PM IST(+5.30 GMT)
LIKE US ON FACEBOOK
 
+