File upload in ASP.NET MVC


File upload in ASP.NET MVC


Here is a sample for handling upload of a file, In your MVC application. In this sample i used the Dialog box of JQuery, where user will select the file and will click upload

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    

<h2>Files uploaded to server</h2>    

<div id="dialog" title="Upload files">        
    <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {%><br />
        <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br />
        <p><input type="submit" value="Upload file" /></p>        
    <% } %>    
<a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Upload File</a>

Then we have to handle this request in the respective controller which is specified in BeginForm of our above code (FileContoller) and action name (Upload). Following will be our code in the FileController Controller for the Upload action

public void Upload()
foreach (string inputTagName in Request.Files)
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
, Path.GetFileName(file.FileName));

RedirectToAction("Index", "File");

Download the sample code from here

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s