Home > DeveloperSection > Blogs > File Upload for any specific file in MVC

File Upload for any specific file in MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
0 Comment(s)
 2626  View(s)
Rate this:

File Upload for any specific file in MVC

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);

        }

        else

            alert("file not supported!");

    }

</script>

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();

}

[HttpPost]

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:


Don't want to miss updates? Please click the below button!

Follow MindStick