Вы можете использовать IFormFile
для получения файла. А затем сохранить URL-адрес пути к файлу в вашей базе данных, используя ядро EF.Не забудьте создать папку myFiles
, в которой сначала будут сохранены загруженные файлы в wwwroot
.
Вы можете обратиться к руководству по Загрузка файлов в ASP.NET Core
Ниже приведена простая демонстрация:
Модели:
public class Engineer
{
public int Id { get; set; }
public string Name { get; set; }
public string FilePath { get; set; }
}
public class EngineerVM
{
public string Name { get; set; }
public IFormFile File{ get; set; }
}
Вид:
@model EngineerVM
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
<div class="form-group">
<div class="col-md-10">
<input type="text" asp-for="Name" />
</div>
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file"/>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Save" />
</div>
</div>
</form>
Контроллер:
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnv;
private readonly ApplicationDbContext _context;
public HomeController(IHostingEnvironment hostingEnv,ApplicationDbContext context)
{
_hostingEnv = hostingEnv;
_context = context;
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(EngineerVM engineerVM)
{
if (engineerVM.File != null)
{
//upload files to wwwroot
var fileName = Path.GetFileName(engineerVM.File.FileName);
//judge if it is pdf file
string ext =Path.GetExtension(engineerVM.File.FileName);
if(ext.ToLower() != ".pdf")
{
return View();
}
var filePath = Path.Combine(_hostingEnv.WebRootPath, "images", fileName);
using (var fileSteam = new FileStream(filePath, FileMode.Create))
{
await engineerVM.File.CopyToAsync(fileSteam);
}
//your logic to save filePath to database, for example
Engineer engineer = new Engineer();
engineer.Name = engineerVM.Name;
engineer.FilePath = filePath;
_context.Engineers.Add(engineer);
await _context.SaveChangesAsync();
}
else
{
}
return View();
}
}
Если вы хотитечтобы скачать файл, вы можете использовать следующий код:
индекс просмотра:
@model IEnumerable<Engineer>
<td>
<a asp-action="DownloadFile" asp-route-filePath="@item.FilePath">Download</a>
</td>
действие:
public IActionResult DownloadFile(string filePath)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
string fileName = "myfile.pdf";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
//For preview pdf and the download it use below code
// var stream = new FileStream(filePath, FileMode.Open);
//return new FileStreamResult(stream, "application/pdf");
}