using Microsoft.EntityFrameworkCore; using vendorApproverBackend.Data; using vendorApproverBackend.Entities; using vendorApproverBackend.Interfaces; namespace vendorApproverBackend.Services { public class FileStorageService : IFileStorageService { private readonly IWebHostEnvironment _env; private readonly DataContext _context; public FileStorageService(IWebHostEnvironment env, DataContext context) { _env = env; _context = context; } private string GetAndEnsureWebRootPath() { string contentRootPath = _env.ContentRootPath; string webRootPath = Path.Combine(contentRootPath, "wwwroot"); if (!Directory.Exists(webRootPath)) { Directory.CreateDirectory(webRootPath); } return webRootPath; } public async Task SaveFileAsync(IFormFile file, string subDirectory) { var webRootPath = GetAndEnsureWebRootPath(); var targetDirectory = Path.Combine(webRootPath, subDirectory); if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } var fileExtension = Path.GetExtension(file.FileName); var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}"; var fullFilePath = Path.Combine(targetDirectory, uniqueFileName); using (var stream = new FileStream(fullFilePath, FileMode.Create)) { await file.CopyToAsync(stream); } var fileModel = new FileModel { Name = file.FileName, Url = $"/{subDirectory.Replace('\\', '/')}/{uniqueFileName}", Type = file.ContentType, Size = file.Length }; _context.FileModels.Add(fileModel); await _context.SaveChangesAsync(); return fileModel; } public async Task DeleteFileAsync(long fileId) { var fileModel = await _context.FileModels.FindAsync(fileId); if (fileModel == null) { return; } var webRootPath = GetAndEnsureWebRootPath(); var physicalPath = Path.Combine(webRootPath, fileModel.Url.TrimStart('/')); // This part remains the same. if (File.Exists(physicalPath)) { File.Delete(physicalPath); } _context.FileModels.Remove(fileModel); await _context.SaveChangesAsync(); } public async Task> SaveAllAsync(List files, string subDirectory) { var savedFiles = new List(); foreach (var file in files) { var savedFile = await SaveFileAsync(file, subDirectory); savedFiles.Add(savedFile); } return savedFiles; } public async Task GetFileByIdAsync(long fileId) { return await _context.FileModels.FindAsync(fileId); } public async Task> GetFilesByIdsAsync(IEnumerable fileIds) { return await _context.FileModels .Where(fm => fileIds.Contains(fm.Id)) .ToListAsync(); } } }