This commit is contained in:
2026-03-25 14:55:34 +08:00
commit 2c44b3a4b2
131 changed files with 7453 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
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);
}
}