Hi hnmahant,
Check this example. Now please take its reference and correct your code.
Model
public class AccountViewModels
{
public string Photo { get; set; }
public HttpPostedFileBase PhotoUpload { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(AccountViewModels viewModel)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (viewModel.PhotoUpload != null)
{
string fileName = Path.GetFileName(viewModel.PhotoUpload.FileName);
viewModel.PhotoUpload.SaveAs(path + fileName);
// Insert in Database.
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO Files (FileName,Path,Photo) VALUES(@FileName,@Path,@Photo)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(fileName));
cmd.Parameters.AddWithValue("@Path", "~/Uploads/" + fileName);
cmd.Parameters.AddWithValue("@Photo", viewModel.Photo);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
return View();
}
}
View
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<_299021_FileUpload_Save_Path.Models.AccountViewModels>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
</head>
<body>
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input type="text" name="Photo" />
<br />
<input type="file" name="PhotoUpload" />
<hr />
<input type="submit" value="Upload" />
<%} %>
</body>
</html>
Screenshot