Thursday, 16 May 2013

Uploading a file to Server in Asp.net MVC 3 /4.



View page:


@using (Html.BeginForm("Index", "MyController", FormMethod.Post , new { enctype = "multipart/form-data" }))
{
//  Controls for your Model........(see below)

 <div>
                <div class="innerLeftContainer">
                    <label >Full Name:</label>
                </div>
                <div class="innerRightContainer">
                    @Html.TextBoxFor(model => model.FullName, new {@class = "inputTextBox"})
                    @Html.ValidationMessageFor(model=>model.FullName)
                </div>
            </div>


<div id="dvUpload">
                <div class="innerLeftContainer">
                    <label>Upload Document:</label>
                </div>
                    <div class="innerRightContainer">
                        <input type="file" id="DocumentUpload" name="file" />
                    </div>
            </div>


}


Note: The Form Method and the enctype is highly required for uploading your file to the server orthrwise you will always get the HttpPostedFileBase as null.


Action Method: ( in the Controller)
 [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                if (fileName != null)
                {
                    // store the file inside ~/App_Data/uploads folder
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                }
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
        }

No comments:

Post a Comment