66 lines
2.0 KiB
C#
66 lines
2.0 KiB
C#
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.Extensions.Options;
|
|
using StopShopping.Services.Extensions;
|
|
using StopShopping.Services.Models;
|
|
using StopShopping.Services.Models.Req;
|
|
using StopShopping.Services.Models.Resp;
|
|
|
|
namespace StopShopping.Services.Implementions;
|
|
|
|
public class FileService : IFileService
|
|
{
|
|
public FileService(IOptions<AppOptions> appOptions,
|
|
IWebHostEnvironment webHostEnvironment)
|
|
{
|
|
_appOptions = appOptions.Value;
|
|
_env = webHostEnvironment;
|
|
}
|
|
|
|
private readonly AppOptions _appOptions;
|
|
private readonly IWebHostEnvironment _env;
|
|
|
|
public async Task<ApiResponse<FileUpload>> 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);
|
|
|
|
FileUpload result = new()
|
|
{
|
|
NewName = newFullName,
|
|
Url = GetFileUrl(payload.Scences, newFullName)
|
|
};
|
|
|
|
return new ApiResponse<FileUpload>(result);
|
|
}
|
|
|
|
public string GetFileUrl(UploadScences scences, string fileName)
|
|
{
|
|
var relativeToRootPath = GetRelativeToRootPath(scences, fileName);
|
|
|
|
return $"{_appOptions.DomainPath}/{relativeToRootPath.Replace(Path.DirectorySeparatorChar, '/')}";
|
|
}
|
|
|
|
private string GetRelativeToRootPath(UploadScences scences, string fileName = "")
|
|
{
|
|
return Path.Combine(
|
|
"images",
|
|
scences.GetTargetDirectory(),
|
|
fileName);
|
|
}
|
|
}
|