In this blog I'm trying to exploring the concept of File Upload for any specify files such as PDF.

File upload is very useful functionality in web application. Here is a simple implementation of file upload in ASP.NET MVC4.

Create a View for file upload:

Add a view (Index) and create a file upload control with the help of HTML as shown below:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "frmUploadFile", @enctype = "multipart/form-data" }))
    <input type="text" id="txtFileName" name="txtFileName" />
    <input type="file" id="fileUpload" name="fileUpload" accept="application/pdf" style="width: 90px;" onchange="validation()" /><br />     <input type="submit" />
    <div style="color:red; font-size:larger;">@ViewBag.Message</div>
Create a JavaScript for Validate file is PDF or not
<script type="text/javascript">
    function validation() {
        var fname = (document.getElementById('fileUpload').value).substring(12);         var re = /(\.pdf)$/i;
        if (re.exec(fname)) {
            document.getElementById('txtFileName').value = (document.getElementById('fileUpload').value).substring(12);         }
            alert("file not supported!");

After adding view and JavaScript the following code in the controller to upload the file on the server:

public ActionResult Index()
     ViewBag.Message = "";
     return View();
public ActionResult Index(HttpPostedFileBase fileUpload)
     var fileName = Path.GetFileName(fileUpload.FileName);
     if (fileUpload != null)
         var newFileName = Guid.NewGuid();
         fileUpload.SaveAs(Server.MapPath("~\\files\\" + newFileName+".pdf"));          ViewBag.Message = "File Upload!";
     return View();

Run this application, you will see the following screen:

  Modified On Sep-18-2014 01:24:17 PM

Leave Comment