1. First create a controller file UpFileController.cs:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Namespace Mvc4study.controllers{
public class Upfilecontroller:controller
{
//
GET:/upfile/
Public ActionResult Index ()
{
return View ();
}
[HttpPost]
public ActionResult upfile ()
{
//project root folder files
string filedir = Server.MapPath ("~/files/") + DateTime.Now.ToString ("yyyy/mm/dd/");// Create a directory based on the date of the upload
if (! System.IO.Directory.Exists (Filedir))//Determine if the directory exists and does not exist to create it.
System.IO.Directory.CreateDirectory (Filedir);
HttpPostedFileBase httpfile = request.files["imgfile"];//get upload file information
Httpfile.saveas (Filedir + httpfile.filename);//Save File
Return JavaScript ("alert (' OK ');");
}
}
}
2. Add the following code to the View layer's page index.cshtml:
@{
Viewbag.title = "File Upload";
}
@using (Html.BeginForm ("Upfile", "Upfile", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
@Html. AntiForgeryToken ()
<p>
Select File Upload:
<input type= "File" name= "imgfile"/>
<input type= "Submit" value= "Submission"/>
</p>
}
So it's done.
ASP. NET MVC upload file