Step1:- Create a New Project in Visual Studio from File menu bar or Prss Ctrl+Shift+N
and Give a name it FileUpload. After Creating project create a folder with name 'UploadedFiles' in your project file.
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace FileUpload.Controllers
{
public class FileUploadingController : Controller
{
//
GET: FileUploading
public ActionResult UploadFile()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
file.SaveAs(path);
}
ViewBag.Message = "File Uploaded
Successfully!!";
return View();
}
catch
{
ViewBag.Message = "File upload
failed!!";
return View();
}
}
}
}
UploadFile.cshtml
@{
ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using (Html.BeginForm("UploadFile", "FileUploading", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.TextBox("file", "", new { type = "file" }) <br />
<input type="submit" value="Upload" />
@ViewBag.Message
</div>
}
No comments:
Post a Comment