1 using System.Security.Claims; 2 using Microsoft.AspNetCore.Authorization; 3 using Microsoft.AspNetCore.Mvc; 4 using Vault.Web.Data; 5 6 namespace Vault.Web.Controllers; 7 8 [ApiController] 9 [Authorize] 10 [Route("api/documents")] 11 public class DocumentsController(VaultDb db, IConfiguration config) : ControllerBase 12 { 13 [HttpPost] 14 [RequestSizeLimit(20 * 1024 * 1024)] 15 public async Task<IActionResult> Upload(IFormFile file) 16 { 17 var userId = User.FindFirstValue(ClaimTypes.NameIdentifier)!; 18 var folder = Path.Combine(config["Storage:Root"]!, userId); 19 Directory.CreateDirectory(folder); 20 var path = Path.Combine(folder, file.FileName); 21 await using (var stream = System.IO.File.Create(path)) 22 { 23 await file.CopyToAsync(stream); 24 } 25 26 var document = new Document 27 { 28 OwnerId = userId, 29 FileName = file.FileName, 30 ContentType = file.ContentType, 31 StoragePath = path, 32 }; 33 db.Documents.Add(document); 34 await db.SaveChangesAsync(); 35 36 return CreatedAtAction(nameof(Download), new { id = document.Id }, new { document.Id, document.FileName }); 37 } 38 39 [HttpGet("{id:int}")] 40 public async Task<IActionResult> Download(int id) 41 { 42 var document = await db.Documents.FindAsync(id); 43 if (document is null) 44 { 45 return NotFound(); 46 } 47 48 return PhysicalFile(document.StoragePath, document.ContentType); 49 } 50 }