This commit is contained in:
2025-07-24 10:47:20 +02:00
parent df4cd1c8a7
commit 601d99bccd
3 changed files with 72 additions and 2 deletions

View File

@@ -71,7 +71,7 @@ public class UserContentController : ControllerBase
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 406)]
public IActionResult PostNewImage(IFormFile file)
/*public IActionResult PostNewImage(IFormFile file)
{
// Ideally, a hash of the file would be stored somewhere
@@ -113,6 +113,76 @@ public class UserContentController : ControllerBase
// Zwróć powyższy URL
return Ok(new { Status = "ok", Filepath = "miejsce na wspomniany URL" });
}*/
//[RequestSizeLimit(10_000_000)] // np. limit 10 MB możesz zmienić lub pobierać z configu
public IActionResult PostNewImage(IFormFile file)
{
// Obsługa braku pliku
if (file == null || file.Length == 0)
{
return BadRequest(new ErrorDTO
{
Status = "error",
Error_msg = "No file was uploaded."
});
}
// Dozwolone rozszerzenia
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
string fileExtension = Path.GetExtension(file.FileName).ToLower();
if (!allowedExtensions.Contains(fileExtension))
{
return BadRequest(new ErrorDTO
{
Status = "error",
Error_msg = $"Unknown file extension. Allowed: {string.Join(", ", allowedExtensions)}"
});
}
// Sprawdzenie typu MIME (opcjonalnie dokładniejsze)
if (!file.ContentType.StartsWith("image/"))
{
return BadRequest(new ErrorDTO
{
Status = "error",
Error_msg = "Uploaded file is not an image."
});
}
// Ograniczenie rozmiaru pliku przykładowo 5 MB
const long MaxFileSize = 5 * 1024 * 1024;
if (file.Length > MaxFileSize)
{
return BadRequest(new ErrorDTO
{
Status = "error",
Error_msg = $"File size exceeds {MaxFileSize / 1024 / 1024} MB."
});
}
// Generowanie unikalnej nazwy
string uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";
string relativePath = $"/uploads/images/{uniqueFileName}";
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images", uniqueFileName);
// Upewnij się, że katalog istnieje
Directory.CreateDirectory(Path.GetDirectoryName(absolutePath)!);
// Zapis pliku na dysk
using (var stream = new FileStream(absolutePath, FileMode.Create))
{
file.CopyTo(stream);
}
// Zwracany adres URL (np. do użytku w cytacie)
return Ok(new
{
Status = "ok",
Filepath = relativePath
});
}
}

View File

@@ -151,5 +151,5 @@ app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseStaticFiles();
app.Run();

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB