file
This commit is contained in:
46
Webshop.Application/Services/FileUploadService.cs
Normal file
46
Webshop.Application/Services/FileUploadService.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
// src/Webshop.Application/Services/FileUploadService.cs
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Webshop.Application.DTOs;
|
||||
using Webshop.Domain.Interfaces;
|
||||
|
||||
namespace Webshop.Application.Services
|
||||
{
|
||||
public class FileUploadService : IFileUploadService
|
||||
{
|
||||
private readonly IFileStorageService _fileStorageService;
|
||||
|
||||
public FileUploadService(IFileStorageService fileStorageService)
|
||||
{
|
||||
_fileStorageService = fileStorageService;
|
||||
}
|
||||
|
||||
public async Task<ServiceResult<FileUploadResultDto>> UploadFileAsync(IFormFile file)
|
||||
{
|
||||
if (file == null || file.Length == 0)
|
||||
{
|
||||
return ServiceResult.Fail<FileUploadResultDto>(ServiceResultType.InvalidInput, "Es wurde keine Datei hochgeladen.");
|
||||
}
|
||||
|
||||
if (!file.ContentType.StartsWith("image/"))
|
||||
{
|
||||
return ServiceResult.Fail<FileUploadResultDto>(ServiceResultType.InvalidInput, "Nur Bilddateien sind erlaubt.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
var fileUrl = await _fileStorageService.SaveFileAsync(stream, file.FileName, file.ContentType);
|
||||
|
||||
var resultDto = new FileUploadResultDto { Url = fileUrl };
|
||||
return ServiceResult.Ok(resultDto);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Hier könntest du den Fehler loggen (z.B. bei Festplattenproblemen)
|
||||
return ServiceResult.Fail<FileUploadResultDto>(ServiceResultType.Failure, $"Beim Speichern der Datei ist ein interner Fehler aufgetreten: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
18
Webshop.Application/Services/IFileUploadService.cs
Normal file
18
Webshop.Application/Services/IFileUploadService.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
// src/Webshop.Application/Services/IFileUploadService.cs
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Webshop.Application;
|
||||
using Webshop.Application.DTOs;
|
||||
|
||||
namespace Webshop.Application.Services
|
||||
{
|
||||
public interface IFileUploadService
|
||||
{
|
||||
/// <summary>
|
||||
/// Validiert und speichert eine hochgeladene Datei.
|
||||
/// </summary>
|
||||
/// <param name="file">Die per HTTP-Request hochgeladene Datei.</param>
|
||||
/// <returns>Ein ServiceResult, das bei Erfolg die URL der Datei enthält.</returns>
|
||||
Task<ServiceResult<FileUploadResultDto>> UploadFileAsync(IFormFile file);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user