Sometimes we require to upload the images on the server folder for a specific requirement, so by considering this requirement I have decided to write this article. Let's start it step by step.
Step 1: Create an ASP.NET MVC Application.
Now let us start with a step by step approach to the creation of a simple ASP.NET MVC application as in the following:- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- Click "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
Step 2: Create Model Class
Now let us create the model class named FileUploadModel.cs by right clicking on the Models folder as in the following screenshot:Write the following code into the FileUploadModel.cs as follows
FileUploadModel.cs
public class FileUploadModel { [DataType(DataType.Upload)] [Display(Name = "Upload File")] [Required(ErrorMessage = "Please choose file to upload.")] public string file { get; set; } }
Now let us add the MVC 5 controller as in the following screenshot:
Note:
The controller name must have a suffix as 'Controller' after specifying the name of the controller. Now let's modify the default code in FileUploadController.cs to read uploaded files. There are many ways to read the uploaded files in the controller, but in this article we will learn two ways to read the uploaded files into the controller which are listed below,
- HttpRequestBase: We can use HttpRequestBase class property named Request to get collection of files or single file.
- HttpPostedFileBase: This is the easiest way to read the uploaded files into the controller .
Now let's open the FileUploadController.cs class file and write the following code to read the file using HttpRequestBase class.
[HttpPost] public ActionResult UploadFiles(HttpPostedFileBase file) { if (ModelState.IsValid) { try { //Method 2 Get file details from HttpPostedFileBase class if (file != null) { string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName)); file.SaveAs(path); } ViewBag.FileStatus = "File uploaded successfully."; } catch (Exception) { ViewBag.FileStatus = "Error while file uploading."; ; } } return View("Index"); }
Following is the whole source code of FileUploadController.cs file which will look like as follows,
using System; using System.IO; using System.Web; using System.Web.Mvc; namespace UploadingFilesUsingMVC.Controllers { public class FileUploadController : Controller { // GET: FileUpload public ActionResult Index() { return View(); } [HttpPost] public ActionResult UploadFiles(HttpPostedFileBase file) { if (ModelState.IsValid) { try { if (file != null) { string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName)); file.SaveAs(path); } ViewBag.FileStatus = "File uploaded successfully."; } catch (Exception) { ViewBag.FileStatus = "Error while file uploading."; } } return View("Index"); } } }
Step 4 : Creating view named Index using FileUploadModel class
Right click on The View folder of created application and choose add view, select FileUploadModel class and choose create scaffolding template,Click on Add button, then it will create the view named index. Now open the Index.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,
Index.cshtml
@model UploadingFilesUsingMVC.Models.FileUploadModel @{ ViewBag.Title = "www.compilemode.com"; } @using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} }) @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Upload" class="btn btn-primary" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10 text-success"> @ViewBag.FileStatus </div> </div> </div> } <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Step 4 : Create a folder named UploadedFiles or as you wish to save uploaded files
Right click on created ASP.NET MVC application, solution explorer and choose add new item, then Add New Folder. After adding the model, view, controller and UploadedFiles folder to save the file. Solution explorer will look like as follows,Now we have done all coding to upload files.
Step 5: Now run the application.
After running the application initial screen will look as follows
Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,
Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,
Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,
I hope from all the preceding examples we have learned how to upload files on server folder.
Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,
Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,
Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,
I hope from all the preceding examples we have learned how to upload files on server folder.
Note:
- HttpPostedFileBase instance name must be a file.
- Model class property name must be file so it can generate the input type file .
- Its important to define enctype = "multipart/form-data" in form action otherwise file value will be null in controller .
- Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.
Don't Forget To
- Subscribe my YouTube Chanel Compile Mode
- Subscribe free email alert of compilemode.com
- Like Facebook page .
- Follow on Twitter.
- Share to your friends
Post a Comment