In this article, I will explore how to upload a file using ASP.NET MVC. Since MVC framework does not use server control, so it will be interesting to see how file upload works in MVC.
Here is my view that renders a form for uploading files
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
FileUpload
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>FileUpload</h2>
<% using (Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />
<%} %>
</asp:Content>
Now, I will write a controller for file upload and here is my FileUploadController.cs
[HandleError]
public class FileUploadController : Controller
{
public ActionResult FileUpload()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
}
One thing to note that the controller has two overloaded methods of a FileUpload. The first ActionResult FileUpload is just to render the form and the method that attributed with [AcceptVerbs(HttpVerbs.Post)] will upload the file. Here is the output form for uploading files
Summary
In this article, you learned a HTTP File Upload with ASP.NET MVC.