Create.cshtml:
@page
@model RazorAPP.Pages.File.CreateModel
@{
ViewData["Title"] = "Create";
}
Create
AppFile
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Create.cshtml.cs:
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using RazorAPP.Data;
namespace RazorAPP.Pages.File
{
public class CreateModel : PageModel
{
private readonly RazorAPP.Data.ApplicationDbContext _context;
private readonly IWebHostEnvironment _hostenvironment;
public CreateModel(RazorAPP.Data.ApplicationDbContext context, IWebHostEnvironment webHostEnvironment)
{
_context = context;
_hostenvironment = webHostEnvironment;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public FileViewModel FileUpload { get; set; }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
//upload file to folder
if (FileUpload.FormFile.Length > 0)
{
using (var stream = new FileStream(Path.Combine(_hostenvironment.WebRootPath, "uploadfiles", FileUpload.FormFile.FileName), FileMode.Create))
{
await FileUpload.FormFile.CopyToAsync(stream);
}
}
//save image to database.
using (var memoryStream = new MemoryStream())
{
await FileUpload.FormFile.CopyToAsync(memoryStream);
// Upload the file if less than 2 MB
if (memoryStream.Length < 2097152)
{
var file = new AppFile()
{
FileName = FileUpload.FormFile.FileName,
Content = memoryStream.ToArray()
};
_context.File.Add(file);
await _context.SaveChangesAsync();
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
return RedirectToPage("./Index");
}
}
}