mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-15 08:30:06 +01:00
feat: image deletion endpoint
handles image deletion from disk as well, if a file is sourced locally
This commit is contained in:
@@ -37,7 +37,7 @@ public class UserContentController : ControllerBase
|
||||
/// Requires authorization with a JWT, has CORS set.
|
||||
/// </remarks>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
[HttpGet]
|
||||
[HttpGet("images")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(typeof(List<Image>), 200)]
|
||||
@@ -66,7 +66,7 @@ public class UserContentController : ControllerBase
|
||||
/// <response code="400">Returned when request does not contain a file or the file is blank</response>
|
||||
/// <response code="413">Returned when image size is too large</response>
|
||||
/// <response code="415">Returned when file extension/mimetype is unknown</response>
|
||||
[HttpPost]
|
||||
[HttpPost("images")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(200)]
|
||||
@@ -149,5 +149,52 @@ public class UserContentController : ControllerBase
|
||||
});
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
// - from db
|
||||
_db.Images.Remove(image);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// Return ok
|
||||
return Ok(new { Status = "ok" });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user