Create a new MVC Project (Internet Application).
Add a new Controller, Name it as "file". Write the following code in it.
- public ActionResult file()
- {
- return View();
- }
- [HttpPost]
- public ActionResult file(IEnumerable < HttpPostedFileBase > file)
- {
- for (int i = 0; i < Request.Files.Count; i++)
- {
- if (Request.Files[i] != null && Request.Files[i].ContentLength > 0) try {
- string path = Path.Combine(Server.MapPath("~/Content/Files"),
- Path.GetFileName(Request.Files[i].FileName));
- Request.Files[i].SaveAs(path);
- ViewBag.Message = "File uploaded successfully";
- } catch (Exception ex) {
- ViewBag.Message = "ERROR:" + ex.Message.ToString();
- } else {
- ViewBag.Message = "You have not specified a file.";
- }
- }
- return View();
- }
Right click on the file method name and create a view named "file".
- View------ > file.cshtml
- Add the following code in the View: -
-
- @ {
- ViewBag.Title = "file";
- } < h2 > Upload file < /h2>
- t;br/ > @using(Html.BeginForm("file", "file", FormMethod.Post,
- new {
- enctype = "multipart/form-data"
- })) { < input type = "file"
- name = "file"
- id = "file"
- multiple = "multiple" / > < br / > < input type = "submit"
- value = "Upload file" / > < br / > < br / > @ViewBag.Message
- }
Note
In the controller, dont forget to add "using System.IO;" reference Also add a new folder named "Files" in the content folder of the project. Refer the attached file in case u find any difficulties.