Wednesday, August 15, 2018

How to Upload Files in ASP.NET MVC

 Upload Files In ASP.NET MVC
Here i am going to explain File Upload example in ASP.Net MVC  
 Below code is quite limited and simple functionality for single file upload, and it will work in any browser.  
 Before uploading the file, we will check whether Directory exists if not exist then the Directory will be created.  
 View  
 View consists of an HTML form containing the submite button, which open a select file dialog, and Submit, which sends the chosen file to  
 the server in a POST request.  
 <html>  
 <head>  
   <meta name="viewport" content="width=device-width"/>  
   <title>Index</title>  
 </head>  
 <body>  
   <div>  
     @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
     {  
       <span>Select File:</span>  
       <input type="file" name="postedFile"/>  
       <hr/>  
       <input type="submit" value="Upload"/>  
       <br/>  
       <span style="color:green">@ViewBag.Message</span>  
     }  
   </div>  
 </body>  
 </html>  
 Controller  
 public class HomeController : Controller  
 {  
   // GET: Home  
   [HttpGet]  
   public ActionResult Index()  
   {  
     return View();  
   }   
   [HttpPost]  
   public ActionResult Index(HttpPostedFileBase postedFile)  
   {  
     if (postedFile != null)  
     {  
       string path = Server.MapPath("~/Upload/");  
       if (!Directory.Exists(path))  
       {  
         Directory.CreateDirectory(path);  
       }   
       postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));  
       ViewBag.Message = "File uploaded successfully.";  
     }   
     return View();  
   }  
 }  

0 comments:

Post a Comment