2020-09-18 05:35:20 +00:00
using Microsoft.AspNetCore.Mvc.RazorPages ;
using Snootalogue.Data ;
using Microsoft.AspNetCore.Mvc ;
using System.Net ;
using System.Linq ;
using System.IO ;
using System.Threading.Tasks ;
using Microsoft.EntityFrameworkCore ;
using Snootalogue.ViewModels ;
using Snootalogue.Models ;
namespace Snootalogue.Pages {
public class UploadModel : PageModel {
private readonly SnootalogueContext _context ;
[BindProperty]
public UploadDocument ud { get ; set ; }
public UploadModel ( SnootalogueContext context ) {
_context = context ;
}
[HttpPost]
// [DisableFormValueModelBinding]
// [ValidateAntiForgeryToken]
public async Task < IActionResult > OnPostAsync ( UploadDocument ud ) {
if ( ! ModelState . IsValid ) {
return Page ( ) ;
}
if ( ud . UploadedFile = = null ) {
return Page ( ) ;
}
2020-09-20 04:05:18 +00:00
var id = Document . NewID ( _context ) ;
2020-09-18 05:35:20 +00:00
// var uploadDirectory = Path.Combine(filename);
2020-09-20 04:12:41 +00:00
var uploadDirectory = Path . Combine ( "wwwroot" , "Content" ) ;
2020-09-20 04:05:18 +00:00
var destination = Path . Combine ( uploadDirectory , $"{id}.pdf" ) ;
2020-09-18 05:35:20 +00:00
using ( var fs = new FileStream ( destination , FileMode . Create ) ) {
await ud . UploadedFile . CopyToAsync ( fs ) ;
}
// Document d = _context.Document.
Document d = new Document {
2020-09-20 04:05:18 +00:00
ID = id ,
2020-09-18 05:35:20 +00:00
Title = ud . Title ,
Authors = ud . Authors . Split ( "," ) . ToList < string > ( ) ,
Category = ud . Category ,
Tags = string . IsNullOrWhiteSpace ( ud . Tags ) ? null : ud . Tags . Split ( "," ) . ToList < string > ( ) ,
Notes = ud . Notes ,
Read = ud . Read ,
2020-09-20 04:05:18 +00:00
Filename = WebUtility . HtmlEncode ( ud . UploadedFile . FileName )
2020-09-18 05:35:20 +00:00
} ;
_context . Document . Add ( d ) ;
try {
await _context . SaveChangesAsync ( ) ;
}
catch ( DbUpdateConcurrencyException e ) {
// TODO: handle it like https://github.com/dotnet/AspNetCore.Docs/blob/master/aspnetcore/tutorials/razor-pages/razor-pages-start/sample/RazorPagesMovie30/Pages/Movies/Edit.cshtml.cs#L56
throw e ;
}
return RedirectToPage ( "/Index" ) ;
}
}
}