This commit is contained in:
Tizian.Breuch
2025-09-25 14:57:13 +02:00
parent db2073dbd1
commit 195d794703
4 changed files with 80 additions and 30 deletions

View File

@@ -2,10 +2,10 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
using Webshop.Application;
using Webshop.Application.DTOs;
using Webshop.Domain.Interfaces;
using Webshop.Application.Services; // Namespace für den neuen Service
namespace Webshop.Api.Controllers.Admin
{
@@ -14,34 +14,27 @@ namespace Webshop.Api.Controllers.Admin
[Authorize(Roles = "Admin")]
public class FileUploadController : ControllerBase
{
private readonly IFileStorageService _fileStorageService;
private readonly IFileUploadService _fileUploadService;
public FileUploadController(IFileStorageService fileStorageService)
public FileUploadController(IFileUploadService fileUploadService)
{
_fileStorageService = fileStorageService;
_fileUploadService = fileUploadService;
}
[HttpPost("upload")]
public async Task<ActionResult<FileUploadResultDto>> UploadImage(IFormFile file)
[ProducesResponseType(typeof(FileUploadResultDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UploadImage(IFormFile file)
{
if (file == null || file.Length == 0)
var result = await _fileUploadService.UploadFileAsync(file);
return result.Type switch
{
return BadRequest(new { Message = "Es wurde keine Datei hochgeladen." });
}
// Optional: Validierung des Dateityps
if (!file.ContentType.StartsWith("image/"))
{
return BadRequest(new { Message = "Nur Bilddateien sind erlaubt." });
}
// Öffne einen Stream aus der hochgeladenen Datei
await using var stream = file.OpenReadStream();
// Speichere die Datei mit dem Service und erhalte die URL
var fileUrl = await _fileStorageService.SaveFileAsync(stream, file.FileName, file.ContentType);
return Ok(new FileUploadResultDto { Url = fileUrl });
ServiceResultType.Success => Ok(result.Value),
ServiceResultType.InvalidInput => BadRequest(new { Message = result.ErrorMessage }),
_ => StatusCode(StatusCodes.Status500InternalServerError, new { Message = result.ErrorMessage ?? "Ein unerwarteter Fehler ist aufgetreten." })
};
}
}
}