public class Files { [Key] public int DocumentId { get; set; } public string Name { get; set; } public string FileType { get; set; } public byte[] DataFiles { get; set; }
<pre>public class DemoController : Controller { private readonly ApplicationDbContext _context; public DemoController(ApplicationDbContext context) { _context = context; } public IActionResult Index() { var result = _context.Files.ToList(); return View(result); } [HttpPost] public IActionResult Index(IFormFile files) { if (files != null) { if (files.Length > 0) { //Getting FileName var fileName = Path.GetFileName(files.FileName); //Getting file Extension var fileExtension = Path.GetExtension(fileName); // concatenating FileName + FileExtension var newFileName = String.Concat(Convert.ToString(Guid.NewGuid()), fileExtension); var objfiles = new Files() { DocumentId = 0, Name = newFileName, FileType = fileExtension, }; using (var target = new MemoryStream()) { files.CopyTo(target); objfiles.DataFiles = target.ToArray(); } _context.Files.Add(objfiles); _context.SaveChanges(); } } return View(); } public IActionResult DownloadImage(int id) { byte[] bytes; string fileName, contentType; var item = _context.Files.FirstOrDefault(c => c.DocumentId == id); if (item != null) { fileName = item.Name; contentType = item.FileType; bytes = item.DataFiles; return File(bytes, contentType, fileName); } return Ok("Can't find the File"); } } }
<pre>@model List<Info.Models.Files> @{ ViewData["Title"] = "Index"; } <h1>Index</h1> <div class="row"> <div class="col-md-5"> <form method="post" enctype="multipart/form-data" asp-controller="Demo" asp-action="Index"> <div class="form-group"> <div class="col-md-10"> <p>Upload file</p> <input class="form-control" name="files" type="file" /> </div> </div> <div class="form-group"> <div class="col-md-10"> <input class="btn btn-success" type="submit" value="Upload" /> </div> </div> </form> </div> </div> <ul> @foreach (var item in Model) { <li> <a asp-action="DownloadImage" asp-route-filename="@item.Name"> @item.Name </a> </li> } </ul>
return View()
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)