using Fake.Application; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Xhs; using Oms.Application.Shared; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.XhsAggregate.Entities; using Oms.Domain.XhsAggregate.Repositories; namespace Oms.Application.Services.Xhs; [ApiExplorerSettings(GroupName = "OMS-Xhs")] public class XhsMediaService : ApplicationService { private IXhsMediaRepository MediaRepository => LazyServiceProvider.GetRequiredService(); private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); private IWebHostEnvironment WebHostEnvironment => LazyServiceProvider.GetRequiredService(); /// /// 上传媒体文件 /// [HttpPost("/xhs/media/upload")] public async Task UploadAsync(IFormFile file) { if (file == null || file.Length == 0) { throw new BusinessException("请选择文件"); } var customerId = await OmsSessionHelper.ResolveXhsCustomerIdAsync(CustomerRepository, CurrentUser); var uploadsRoot = Path.Combine(WebHostEnvironment.WebRootPath ?? "wwwroot", "uploads", "xhs", customerId.ToString()); Directory.CreateDirectory(uploadsRoot); var ext = Path.GetExtension(file.FileName); var storedName = $"{Guid.NewGuid():N}{ext}"; var fullPath = Path.Combine(uploadsRoot, storedName); await using (var stream = File.Create(fullPath)) { await file.CopyToAsync(stream); } var relativePath = Path.Combine("uploads", "xhs", customerId.ToString(), storedName).Replace('\\', '/'); var publicUrl = $"/{relativePath}"; var media = new XhsMedia { CustomerId = customerId, FileName = file.FileName, StoragePath = relativePath, PublicUrl = publicUrl, MimeType = file.ContentType, FileSizeBytes = file.Length }; await MediaRepository.InsertAsync(media); return new XhsMediaUploadOutput { MediaId = media.Id, PublicUrl = publicUrl }; } }