I have showed you how to upload file in asp.net. In the same way we can upload file in asp.net mvc4 with little difference.
Now for this article we create a new mvc application and create a new control and view for this control action.
Controller Code:-
Here I given a controller name "FileUploadController".
View Code:-
After creating a view and controller, you create a images folder where you want to save the file.
Now for this article we create a new mvc application and create a new control and view for this control action.
Controller Code:-
Here I given a controller name "FileUploadController".
public class FileUploadController
: Controller
{
/// <summary>
/// file upload in mvc 4
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
return View();
}
/// <summary>
/// post method for file uploading
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
//* single file uploading method
try
{
//* get the file name
string fileName = System.IO.Path.GetFileName(file.FileName);
//* save the file on server
file.SaveAs(Server.MapPath("~/Images/"
+ fileName));
ViewBag.Message
= "File saved successfully";
}
catch
{
ViewBag.Message
= "Error while File uploading?";
}
return View();
}
}
Now you create a view according to controller Action method.View Code:-
@{
ViewBag.Title = "File Upload in MVC4";
}
<h2>Index</h2>
@using (Html.BeginForm("Index","FileUpload", FormMethod.Post,
new {enctype="multipart/form-data"}))
{
<input name="file" type="file" value="" />
<input type="submit" name="submit" value="upload your images" />
<div>@ViewBag.Message</div>
}
After creating a view and controller, you create a images folder where you want to save the file.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.