mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 11:00:06 +01:00
Compare commits
3 Commits
3e823fb37b
...
user_conte
| Author | SHA1 | Date | |
|---|---|---|---|
| 11d24dcc11 | |||
| bb9bdcfaa0 | |||
| 601d99bccd |
@@ -37,7 +37,7 @@ public class UserContentController : ControllerBase
|
|||||||
/// Requires authorization with a JWT, has CORS set.
|
/// Requires authorization with a JWT, has CORS set.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <response code="200">Returned on valid request</response>
|
/// <response code="200">Returned on valid request</response>
|
||||||
[HttpGet]
|
[HttpGet("images")]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[EnableCors]
|
[EnableCors]
|
||||||
[ProducesResponseType(typeof(List<Image>), 200)]
|
[ProducesResponseType(typeof(List<Image>), 200)]
|
||||||
@@ -60,59 +60,140 @@ public class UserContentController : ControllerBase
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// Allows authorized users to publish images.
|
/// Allows authorized users to publish images.
|
||||||
/// A user-reachable path is returned on success.<br/>
|
/// A user-reachable path and image id is returned on success.<br/>
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <response code="200">Returned on valid request</response>
|
/// <response code="200">Returned on valid request</response>
|
||||||
/// <response code="400">Returned when file extension is unknown</response>
|
/// <response code="400">Returned when request does not contain a file or the file is blank</response>
|
||||||
/// <response code="406">Returned when request does not follow user-provided config</response>
|
/// <response code="413">Returned when image size is too large</response>
|
||||||
[HttpPost]
|
/// <response code="415">Returned when file extension/mimetype is unknown</response>
|
||||||
|
[HttpPost("images")]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
[EnableCors]
|
[EnableCors]
|
||||||
[ProducesResponseType(200)]
|
[ProducesResponseType(200)]
|
||||||
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||||
[ProducesResponseType(typeof(ErrorDTO), 406)]
|
[ProducesResponseType(typeof(ErrorDTO), 413)]
|
||||||
|
[ProducesResponseType(typeof(ErrorDTO), 415)]
|
||||||
public IActionResult PostNewImage(IFormFile file)
|
public IActionResult PostNewImage(IFormFile file)
|
||||||
{
|
{
|
||||||
|
// Obsługa braku pliku
|
||||||
// Ideally, a hash of the file would be stored somewhere
|
if (file == null || file.Length == 0)
|
||||||
// in the database to have a basic redundancy check,
|
{
|
||||||
// but this will do for now. ~eee4
|
return BadRequest(new ErrorDTO
|
||||||
|
{
|
||||||
// A good idea would be to also check the Content-Type
|
|
||||||
// of submitted files. ~eee4
|
|
||||||
|
|
||||||
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
|
|
||||||
|
|
||||||
string fileExtension = Path.GetExtension(file.FileName);
|
|
||||||
if (!allowedExtensions.Contains(fileExtension.ToLower())) {
|
|
||||||
return BadRequest(new ErrorDTO {
|
|
||||||
Status = "error",
|
Status = "error",
|
||||||
Error_msg = $"Unknown file extension. Please use one of the following: {string.Join(", ", allowedExtensions)}"
|
Error_msg = "No file was uploaded."
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO:
|
// Dozwolone rozszerzenia
|
||||||
// https://www.youtube.com/watch?v=6-FNejMrVuk
|
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
|
||||||
|
string fileExtension = Path.GetExtension(file.FileName).ToLower();
|
||||||
|
|
||||||
// Sprawdź, czy plik spełnia ograniczenia:
|
if (!allowedExtensions.Contains(fileExtension))
|
||||||
// 1. Czy rozmiar jest mniejszy od _appsettings["UserContent"]["MaxFileSize"] ?
|
{
|
||||||
|
return StatusCode(415, 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 StatusCode(415, new ErrorDTO
|
||||||
|
{
|
||||||
|
Status = "error",
|
||||||
|
Error_msg = "Uploaded file is not an image."
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Jeśli nie, zwróć ErrorDTO ze wiadomością: $"File size exceeds {_appsettings["UserContent"]["MaxFileSize"]}"
|
// Ograniczenie rozmiaru pliku do tego, ustawionego przez użytkownika
|
||||||
|
int MaxFileSize = int.TryParse(_appsettings.GetSection("UserContent")["MaxFileSize"], out int r)
|
||||||
|
? r
|
||||||
|
: 5 * 1024 * 1024;
|
||||||
|
if (file.Length > MaxFileSize)
|
||||||
|
{
|
||||||
|
return StatusCode(413, 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);
|
||||||
|
|
||||||
// Zapisz plik na dysku z pseudolosową nazwą GUID
|
// 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);
|
||||||
|
}
|
||||||
|
|
||||||
// Wrzucić go do folderu "uploads/images/"
|
// Dodaj do bazy
|
||||||
|
Image image = new Image { Url = relativePath };
|
||||||
|
_db.Images.Add(image);
|
||||||
|
_db.SaveChanges();
|
||||||
|
|
||||||
|
// Zwracany adres URL (np. do użytku w cytacie)
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
Status = "ok",
|
||||||
|
Filepath = relativePath,
|
||||||
|
ImageId = image.Id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Stwórz URL postaci: "/uploads/images/<nazwa pliku>.<rozszerzenie>"
|
// DELETE /api/v1/uc/images/{id}
|
||||||
|
/// <summary>
|
||||||
|
/// [AUTHED] Delete an image
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Deletes an image, granted it exists. <br/>
|
||||||
|
/// <b>Note</b>:
|
||||||
|
/// If the image is a file on disk, it's also deleted.
|
||||||
|
/// </remarks>
|
||||||
|
/// <returns>Json with status</returns>
|
||||||
|
/// <param name="id">Image id which will be deleted</param>
|
||||||
|
/// <response code="200">Returned on valid request</response>
|
||||||
|
/// <response code="404">Returned when no such image exists</response>
|
||||||
|
[HttpDelete("images/{id}")]
|
||||||
|
[Authorize]
|
||||||
|
[EnableCors]
|
||||||
|
[ProducesResponseType(200)]
|
||||||
|
[ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||||
|
public async Task<IActionResult> DeleteImage(int id)
|
||||||
|
{
|
||||||
|
// (Attempt to) find the image
|
||||||
|
Image? image = await _db.Images
|
||||||
|
.FirstOrDefaultAsync(q => q.Id == id);
|
||||||
|
// Failed?
|
||||||
|
if (image == null)
|
||||||
|
return NotFound(new { status = "error", error_msg = "Image not found" });
|
||||||
|
|
||||||
|
// If succeded, remove the image:
|
||||||
|
// - from disk - if saved locally
|
||||||
|
if (!string.IsNullOrEmpty(image.Url)) {
|
||||||
|
if (image.Url.StartsWith("/uploads/images/")) {
|
||||||
|
// delete from disk
|
||||||
|
int fileNameStart = image.Url.LastIndexOf('/');
|
||||||
|
string uniqueFileName = image.Url.Substring(fileNameStart + 1);
|
||||||
|
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images", uniqueFileName);
|
||||||
|
System.IO.File.Delete(absolutePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Zwróć powyższy URL
|
// - from db
|
||||||
return Ok(new { Status = "ok", Filepath = "miejsce na wspomniany URL" });
|
_db.Images.Remove(image);
|
||||||
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
|
// Return ok
|
||||||
|
return Ok(new { Status = "ok" });
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,5 +151,5 @@ app.UseAuthentication();
|
|||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
app.UseStaticFiles();
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|||||||
@@ -36,7 +36,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="uploads\images\" />
|
<Folder Include="wwwroot\uploads\images\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
BIN
wwwroot/uploads/images/42cbadf4-7804-4fde-991c-d56eb1f4a1b4.png
Normal file
BIN
wwwroot/uploads/images/42cbadf4-7804-4fde-991c-d56eb1f4a1b4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Reference in New Issue
Block a user