SPMS_API/SPMS.Infrastructure/Services/LocalFileStorageService.cs

44 lines
1.3 KiB
C#

using Microsoft.Extensions.Configuration;
using SPMS.Application.Interfaces;
namespace SPMS.Infrastructure.Services;
public class LocalFileStorageService : IFileStorageService
{
private readonly string _uploadPath;
private readonly string _baseUrl;
public LocalFileStorageService(IConfiguration configuration)
{
_uploadPath = configuration["FileStorage:UploadPath"] ?? "Uploads";
_baseUrl = configuration["FileStorage:BaseUrl"] ?? "/uploads";
}
public async Task<string> SaveAsync(long serviceId, string fileName, Stream fileStream)
{
var directory = Path.Combine(_uploadPath, serviceId.ToString());
Directory.CreateDirectory(directory);
var uniqueName = $"{Guid.NewGuid():N}_{fileName}";
var fullPath = Path.Combine(directory, uniqueName);
using var output = new FileStream(fullPath, FileMode.Create);
await fileStream.CopyToAsync(output);
return $"{serviceId}/{uniqueName}";
}
public Task DeleteAsync(string filePath)
{
var fullPath = Path.Combine(_uploadPath, filePath);
if (System.IO.File.Exists(fullPath))
System.IO.File.Delete(fullPath);
return Task.CompletedTask;
}
public string GetFileUrl(string filePath)
{
return $"{_baseUrl.TrimEnd('/')}/{filePath}";
}
}