MyImageService is a simple .NET Core service for handling image uploads and deletions. It includes file validation, size checks, and URL generation for stored images.
- Upload images with validation for file type and size.
- Delete images by filename.
- Generate accessible URLs for stored images.
You can install the package via NuGet Package Manager:
Install-Package Ahmed0Tawfik.Services.ImagesOr using .NET CLI:
dotnet add package Ahmed0Tawfik.Services.Images- Install the package (if applicable) or add the service to your project.
- Register the service in your
Startup.csorProgram.csfile.
In your .NET application, register the image service by modifying Program.cs:
using MyImageService;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.RegisterImageServices();
var app = builder.Build();
app.Run();You can inject IUploadFileService into any controller or service where you need file upload functionality.
using Microsoft.AspNetCore.Mvc;
using MyImageService.Interfaces;
[ApiController]
[Route("api/images")]
public class ImageController : ControllerBase
{
private readonly IUploadFileService _uploadFileService;
public ImageController(IUploadFileService uploadFileService)
{
_uploadFileService = uploadFileService;
}
[HttpPost("upload")]
public IActionResult UploadImage([FromForm] IFormFile file)
{
try
{
var url = _uploadFileService.UploadFile(file, Request.Scheme, Request.Host.Value);
return Ok(new { ImageUrl = url });
}
catch (Exception ex)
{
return BadRequest(new { Message = ex.Message });
}
}
[HttpDelete("delete")]
public IActionResult DeleteImage([FromQuery] string fileName)
{
try
{
_uploadFileService.DeleteImage(fileName);
return Ok(new { Message = "Image deleted successfully" });
}
catch (Exception ex)
{
return BadRequest(new { Message = ex.Message });
}
}
}- File Type Validation: Ensures only
.jpg,.jpeg,.png, and.svgfiles are uploaded. - File Size Validation: Ensures file size is between
0 and 2MB. - File Storage: Saves the file under the
Imagesdirectory with a unique GUID filename. - URL Generation: Returns a publicly accessible URL for the uploaded image.
- Extracts the filename from the given URL.
- Checks if the file exists in the
Imagesdirectory. - Deletes the file if it exists; otherwise, throws an exception.
| Exception | Reason |
|---|---|
InvalidFileExtensionException |
If the uploaded file has an invalid extension |
InvalidFileSizeException |
If the file size is not within the allowed limit |
FileDoesNotExistException |
If the file to delete does not exist |
This project is open-source and available under the MIT License.