51 lines
1.8 KiB
C#
51 lines
1.8 KiB
C#
// src/Webshop.Infrastructure/Services/LocalFileStorageService.cs
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using System;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
using Webshop.Domain.Interfaces;
|
|
|
|
namespace Webshop.Infrastructure.Services
|
|
{
|
|
public class LocalFileStorageService : IFileStorageService
|
|
{
|
|
private readonly IWebHostEnvironment _env;
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
|
|
public LocalFileStorageService(IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
|
|
{
|
|
_env = env;
|
|
_httpContextAccessor = httpContextAccessor;
|
|
}
|
|
|
|
public async Task<string> SaveFileAsync(Stream fileStream, string fileName, string contentType)
|
|
{
|
|
// Erstelle einen eindeutigen Dateinamen, um Kollisionen zu vermeiden
|
|
var fileExtension = Path.GetExtension(fileName);
|
|
var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";
|
|
|
|
// Definiere den Speicherort im wwwroot-Ordner
|
|
var uploadsFolderPath = Path.Combine(_env.WebRootPath, "uploads");
|
|
if (!Directory.Exists(uploadsFolderPath))
|
|
{
|
|
Directory.CreateDirectory(uploadsFolderPath);
|
|
}
|
|
|
|
var filePath = Path.Combine(uploadsFolderPath, uniqueFileName);
|
|
|
|
// Speichere den Stream in die Datei
|
|
await using (var outputStream = new FileStream(filePath, FileMode.Create))
|
|
{
|
|
await fileStream.CopyToAsync(outputStream);
|
|
}
|
|
|
|
// Erstelle die öffentliche URL
|
|
var request = _httpContextAccessor.HttpContext.Request;
|
|
var baseUrl = $"{request.Scheme}://{request.Host}";
|
|
var fileUrl = $"{baseUrl}/uploads/{uniqueFileName}";
|
|
|
|
return fileUrl;
|
|
}
|
|
}
|
|
} |