Hi ruben00000,
Refer below sample.
Database
CREATE TABLE [Files]
(
[FileId] [INT] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Name] [VARCHAR](80) NOT NULL,
[Path] [NVARCHAR](200) NOT NULL,
)
Model
public class FileModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Namespaces
using System.Data.SqlClient;
Controller
public class HomeController : Controller
{
private readonly IConfiguration Configuration;
private readonly IWebHostEnvironment Environment;
public HomeController(IConfiguration _configuration, IWebHostEnvironment _environment)
{
this.Configuration = _configuration;
this.Environment = _environment;
}
public IActionResult Index()
{
return View(this.GetFiles());
}
[HttpPost]
public IActionResult UploadFile(IFormFile postedFile)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
// Create folder if not exixsts.
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.GetFileName(postedFile.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
// Save file to folder.
postedFile.CopyTo(stream);
// Save file details with path to Database.
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO Files VALUES (@Name, @Path)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", fileName);
cmd.Parameters.AddWithValue("@Path", "/Uploads/" + fileName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
return RedirectToAction("Index");
}
private List<FileModel> GetFiles()
{
List<FileModel> files = new List<FileModel>();
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT FileId, Name FROM Files", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
files.Add(new FileModel
{
Id = Convert.ToInt32(sdr["FileId"]),
Name = sdr["Name"].ToString()
});
}
}
con.Close();
}
}
return files;
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="UploadFile" enctype="multipart/form-data">
<input type="file" name="postedFile" />
<input id="btnUpload" type="submit" value="Upload" />
</form>
<hr />
<table id="tblFiles" cellpadding="0" cellspacing="0">
<tr>
<th style="width:50px">File ID</th>
<th style="width:120px">File Name</th>
</tr>
@foreach (var file in Model)
{
<tr>
<td>@file.Id</td>
<td>@file.Name</td>
</tr>
}
</table>
</body>
</html>
Screenshots
The Form
Record after insert in database