How to upload file in MVC Dotnet project
How to upload any file(Image, pdf, etc) in your database ?
Here we are taking category example where the following parameter we have to consider is Name, Description, Image.
Step 1: First create your modal class for category
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
namespace Pick_n_Buy.Models
{
public class MdlCategory
{
[Key]
public int ID { get; set; }
[Required]
[Display(Name = “Name”)]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Thumbnail { get; set; }
}
}
Step 2: Create your controller method on the base of this you have to create your view page
public ActionResult AddCategory()
{
return View();
}
Step:3 After creating view, in your view you have to change the following things
replace begin form with the following
@using (Html.BeginForm(“AddCategory”, “Admin”, FormMethod.Post, new { enctype = “multipart/form-data” }))
and replace your thumbnail html code with file type
<input type=”file” name=”file” />
Step 3: write another method in same controller with the same name with [HttpPost] and pass two parameter one is your model that contain name and description parameter data and second one is HttpPostedFilesBase object file that contain our uploaded file description file name , extension and size of the file.
[HttpPost]
public ActionResult AddCategory(MdlCategory mdl, HttpPostedFileBase file)
{
try
{
var allowedextention = new[] { “.jpg”, “.Jpg”, “.jpeg”, “.png” };
if (file != null)
{
var ext = Path.GetExtension(file.FileName);
if (allowedextention.Contains(ext))
{
var filename = Path.GetFileName(file.FileName);
var path = “~/Images/Category_Image/” + filename;
file.SaveAs(Server.MapPath(path));
mdl.Thumbnail = path.Replace(“~/”, “/../”);
}
}
if (ModelState.IsValid)
{
BLL_Category obj = new BLL_Category();
obj.Bll_Add_Category(mdl);
return RedirectToAction(“Category”, “Admin”);
}
return View();
}
catch (Exception)
{
throw;
}
}
Here in above step 3 method our uploaded file save into your mention folder and the path generated is assigned to model object, now model have all parameter data, name, description, and thumbnail path.
Furthermore, you have same Bll, Dal, sqlhelper class method and insert procedure, see previous signup call lecture for this help.
1 thought on “How to upload file in MVC Dotnet project”
Leave a Reply
You must be logged in to post a comment.
Here we are Storing the extension and link of the Image in our database, but how we will show that image in our Layout page when we are displaying the data.