imagefile endpunkt
This commit is contained in:
51
Webshop.Infrastructure/Services/LocalFileStorageService.cs
Normal file
51
Webshop.Infrastructure/Services/LocalFileStorageService.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user