using MediatR; namespace Nashel.Modules.Identity.Application.Commands; public class UploadAvatarCommandHandler : IRequestHandler { private const long MaxFileSize = 5 * 1024 * 1024; // 5MB private static readonly string[] AllowedExtensions = { ".jpg", ".jpeg", ".png" }; public async Task Handle(UploadAvatarCommand request, CancellationToken cancellationToken) { var file = request.File; // Валидация размера if (file.Length > MaxFileSize) throw new InvalidOperationException("Размер файла не должен превышать 5 МБ"); // Валидация формата var extension = Path.GetExtension(file.FileName).ToLowerInvariant(); if (Array.IndexOf(AllowedExtensions, extension) == -1) throw new InvalidOperationException("Допустимые форматы: JPG, PNG"); // Создаем папку uploads если её нет var uploadsPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads"); if (!Directory.Exists(uploadsPath)) Directory.CreateDirectory(uploadsPath); // Генерируем уникальное имя файла var fileName = $"{Guid.NewGuid()}{extension}"; var filePath = Path.Combine(uploadsPath, fileName); // Сохраняем файл using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream, cancellationToken); } // Возвращаем URL return $"/uploads/{fileName}"; } }