60 lines
1.8 KiB
C#
60 lines
1.8 KiB
C#
using Microsoft.Extensions.Options;
|
|
|
|
namespace StopShopping.FileApi.Services.Implementions;
|
|
|
|
public class FileService : IFileService
|
|
{
|
|
public FileService(IOptions<AppOptions> appOptions,
|
|
IWebHostEnvironment webHostEnvironment)
|
|
{
|
|
_appOptions = appOptions.Value;
|
|
_env = webHostEnvironment;
|
|
}
|
|
|
|
private readonly IWebHostEnvironment _env;
|
|
private readonly AppOptions _appOptions;
|
|
|
|
public async Task<ApiResponse<FileUploadResp>> UploadFileAsync(UploadParams payload)
|
|
{
|
|
var newName = Guid.NewGuid().ToString("N").ToLower();
|
|
var extension = Path.GetExtension(payload.File!.FileName);
|
|
var newFullName = $"{newName}{extension}";
|
|
var relativeToRootPath = GetRelativeToRootPath(payload.Scences, newFullName);
|
|
var targetPath = Path.Combine(_env.WebRootPath, GetRelativeToRootPath(payload.Scences));
|
|
|
|
if (!Directory.Exists(targetPath))
|
|
{
|
|
Directory.CreateDirectory(targetPath);
|
|
}
|
|
|
|
using var file = new FileStream(
|
|
Path.Combine(_env.WebRootPath, relativeToRootPath),
|
|
FileMode.CreateNew,
|
|
FileAccess.Write);
|
|
|
|
await payload.File.CopyToAsync(file);
|
|
|
|
FileUploadResp result = new()
|
|
{
|
|
NewName = newFullName,
|
|
Url = GetFileUrl(payload.Scences, newFullName),
|
|
};
|
|
|
|
return new ApiResponse<FileUploadResp>(result);
|
|
}
|
|
|
|
private string GetFileUrl(UploadScences scences, string fileName)
|
|
{
|
|
return $"{_appOptions.Domain}/{GetRelativeToRootPath(scences, fileName)
|
|
.Replace(Path.DirectorySeparatorChar, '/')}";
|
|
}
|
|
|
|
private string GetRelativeToRootPath(UploadScences scences, string fileName = "")
|
|
{
|
|
return Path.Combine(
|
|
"images",
|
|
scences.GetTargetDirectory(),
|
|
fileName);
|
|
}
|
|
}
|