File Upload Basics

There are many components that you can use to upload files from client to server in Asp.net MVC . below I will explore one of the very common approch for uploading files .
When we are uploading file there are only two parts of MVC model get involved .one of view and second one is controller

Users’Steps

  • End user visit the page (View) and choose a file to upload.
  • User clicks on submit and upload get started and up loader packs the file into POST request and send it on server.
  • Action method handle the request and save file to server directory.

Configure Attributes (Optional)

  • maxRequestLength – the request size limit in kilobytes (the default value is 4096 KB).
  • requestLengthDiskThreshold – the limit of data buffered in the server memory in kilobytes (the default value is 80 KB).
  • executionTimeout – the allowed execution time for the request before being automatically shut down by ASP.NET (the default value is 110 seconds).

Note –All above attributes must be define in the <httpRuntime> section

Getting Started

Open visual studio and create a MVC application. Give a name to your application and choose the path where you want to create application

Select MVC template

Add folder

I will add a folder where my all files gets uploaded.

Add a controller

Right click on controller folder and click on add controller

Select MVC 5 Controller -Empty. Click Add.

Give a name to controller

Write the following code in controller

[HttpGet]
publicActionResultUploadFile()
{
return View();
}
[HttpPost]
publicActionResultUploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath(“~/UploadedFiles”), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = “File Uploaded Successfully!!”;
return View();
}
catch
{
ViewBag.Message = “File upload failed!!”;
return View();
}
}

 

Add a View

Right click on UploadFileActionResult. Click on Add View.

Select the empty template. Click add.

Write the following code in the View.

  @{       ViewBag.Title = “UploadFile”;   }
<h2>UploadFile</h2>
@using(Html.BeginForm(“UploadFile”,”Upload”, FormMethod.Post, new { enctype=”multipart/form-data”}))   {
           <div>
             @Html.TextBox(“file”, “”, new {  type= “file”}) <br />
               <input type=”submit” value=”Upload” />
                @ViewBag.Message
         </div>
  }

Explore the Application

Hence, I have just tell how to upload the file in ASP.NET MVC. I hope this article is useful to beggeners .. Now you can check whether application is running properly or not . if you get problems regarding this article. comments below .