Thursday, 30 November 2017

Upload and Save file to Server Folder (Disk) in ASP.Net MVC

Upload and Save file to Server Folder (Disk) in ASP.Net MVC

Description:

In this example we explain that how to upload and file to server folder in asp.net MVC.or how to save uploaded file to the server folder (Disk) in MVC.here we first upload file to the server using Razor MVC.so how to upload file in MVC and save the uploaded file in the server directory using MVC.
Controller:

public class HobbyController : Controller
    {
        // GET: Home
        // GET: Home
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase postedFile)
        {
            if (postedFile != null)
            {
                string path = Server.MapPath("~/Uploads/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
                ViewBag.Message = "File uploaded successfully.";
            }

            return View();
        }
    
    }

View: 

<html>
<head>
    <title>Upload and Save file to Server Folder (Disk) in ASP.Net MVC</title>
</head>
<body>
    <div>
        @using (Html.BeginForm("Index", "Employee", 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>


This entry was posted in :

0 comments:

Post a Comment