diff --git a/Controllers/UserContentController.cs b/Controllers/UserContentController.cs index 59c39bb..94804b8 100644 --- a/Controllers/UserContentController.cs +++ b/Controllers/UserContentController.cs @@ -37,7 +37,7 @@ public class UserContentController : ControllerBase /// Requires authorization with a JWT, has CORS set. /// /// Returned on valid request - [HttpGet] + [HttpGet("images")] [Authorize] [EnableCors] [ProducesResponseType(typeof(List), 200)] @@ -66,7 +66,7 @@ public class UserContentController : ControllerBase /// Returned when request does not contain a file or the file is blank /// Returned when image size is too large /// Returned when file extension/mimetype is unknown - [HttpPost] + [HttpPost("images")] [Authorize] [EnableCors] [ProducesResponseType(200)] @@ -149,5 +149,52 @@ public class UserContentController : ControllerBase }); } + // DELETE /api/v1/uc/images/{id} + /// + /// [AUTHED] Delete an image + /// + /// + /// Deletes an image, granted it exists.
+ /// Note: + /// If the image is a file on disk, it's also deleted. + ///
+ /// Json with status + /// Image id which will be deleted + /// Returned on valid request + /// Returned when no such image exists + [HttpDelete("images/{id}")] + [Authorize] + [EnableCors] + [ProducesResponseType(200)] + [ProducesResponseType(typeof(ErrorDTO), 404)] + public async Task 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" }); + } + }