Project Overview
Tech Stack:
Frontend: Angular
Backend: ASP.NET Core Web API
Database: SQL Server
Features
Upload an image from Angular UI
Save the image in SQL Server (
varbinary(max))Retrieve and display the image
Step 1: SQL Server Database Setup
Create a table to store images:
CREATE TABLE EmployeeImages (
Id INT IDENTITY(1,1) PRIMARY KEY,
FileName NVARCHAR(255),
ContentType NVARCHAR(100),
Data VARBINARY(MAX)
);
Step 2: ASP.NET Core API Setup
2.1 Create ASP.NET Core Web API Project
dotnet new webapi -n ImageUploadApi
cd ImageUploadApi
2.2 Create the Model
Models/EmployeeImage.cs:
namespace ImageUploadApi.Models
{
public class EmployeeImage
{
public int Id { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
}
}
2.3 Create DbContext
Data/AppDbContext.cs:
using ImageUploadApi.Models;
using Microsoft.EntityFrameworkCore;
namespace ImageUploadApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<EmployeeImage> EmployeeImages { get; set; }
}
}
Add connection string in appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=ImageDb;Trusted_Connection=True;TrustServerCertificate=True;"
}
Register DbContext in Program.cs:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
2.4 Create Controller for Image Upload
Controllers/ImagesController.cs:
using ImageUploadApi.Data;
using ImageUploadApi.Models;
using Microsoft.AspNetCore.Mvc;
namespace ImageUploadApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ImagesController : ControllerBase
{
private readonly AppDbContext _context;
public ImagesController(AppDbContext context)
{
_context = context;
}
[HttpPost("upload")]
public async Task<IActionResult> Upload([FromForm] IFormFile file)
{
if(file == null || file.Length == 0)
return BadRequest("No file selected.");
using var ms = new MemoryStream();
await file.CopyToAsync(ms);
var image = new EmployeeImage
{
FileName = file.FileName,
ContentType = file.ContentType,
Data = ms.ToArray()
};
_context.EmployeeImages.Add(image);
await _context.SaveChangesAsync();
return Ok(new { image.Id });
}
[HttpGet("{id}")]
public async Task<IActionResult> GetImage(int id)
{
var image = await _context.EmployeeImages.FindAsync(id);
if(image == null) return NotFound();
return File(image.Data, image.ContentType);
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var images = await _context.EmployeeImages.Select(i => new {
i.Id,
i.FileName
}).ToListAsync();
return Ok(images);
}
}
}

Join the conversation! Your thoughts help the community grow.