BudgetApp/BudgetApp.Api/Controllers/UploadController.cs
Martin Svrcina e14e552388 Initial commit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 01:52:43 +01:00

55 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using BudgetApp.PublicModels;
using BudgetApp.Services;
using Microsoft.AspNetCore.Mvc;
namespace BudgetApp.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UploadController(IUploadService uploadService) : ControllerBase
{
private readonly IUploadService _uploadService = uploadService ?? throw new ArgumentNullException(nameof(uploadService));
// Adjust as needed (e.g., 50 MB)
private const long MaxFileSizeBytes = 50 * 1024 * 1024;
/// <summary>
/// Receives a CSV file via multipart/form-data.
/// </summary>
[HttpPost("csv")]
[RequestSizeLimit(MaxFileSizeBytes)]
[Consumes("multipart/form-data")]
public async Task<ActionResult<BaseResponse>> UploadCsv([FromForm] IFormFile file, CancellationToken ct)
{
if (file is null)
return BadRequest("Missing 'file' form field.");
if (file.Length == 0)
return BadRequest("The uploaded file is empty.");
if (file.Length > MaxFileSizeBytes)
return BadRequest($"File too large. Limit is {MaxFileSizeBytes} bytes.");
// Light validation content types for CSV vary by client/OS
var allowedContentTypes = new[]
{
"text/csv",
"application/csv",
"text/plain",
"application/vnd.ms-excel"
};
var hasCsvLikeContentType = allowedContentTypes.Contains(file.ContentType, StringComparer.OrdinalIgnoreCase);
var hasCsvExtension = Path.GetExtension(file.FileName).Equals(".csv", StringComparison.OrdinalIgnoreCase);
if (!hasCsvLikeContentType && !hasCsvExtension)
return BadRequest("Only CSV files are accepted.");
var response = await _uploadService.UploadCsv(file, ct);
// Return whatever metadata/result you need
return Ok(response);
}
}
}