I'm new to dot net core. how can I upload, edit and delete an image into dot net core WEB API?. What should I do, step by step to add/edit or delete an image. I do not have a wwwroot folder. I need to upload an employee profile picture and if I delete an employee, the employee profile picture should also be deleted.
This is my EmployeeController.cs file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EmployeeWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting.Internal;
namespace EmployeeWebApi.Controllers
{
[Route("api/[Controller]")]
[ApiController]
public class EmployeeController:ControllerBase
{
private readonly EmployeeDbContext _context;
public EmployeeController(EmployeeDbContext context)
{
_context = context;
}
//GET: api/Emplyeee
[HttpGet]
public async Task<List<Employee>> GetAllEmployees(){
var employees = await _context.Thanusiga_Employees.ToListAsync();
return employees;
}
//GET: api/Employee/5
[HttpGet("{id}")]
public async Task<ActionResult<Employee>> GetEmployee(int id){
var employee = await _context.Thanusiga_Employees.FindAsync(id);
if( employee == null){
return NotFound();
}
return employee;
}
//POST: api/Employee
[HttpPost]
public async Task<ActionResult<Employee>> PostEmployee(Employee employee){
_context.Thanusiga_Employees.Add(employee);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetEmployee), new {id = employee.Id}, employee);
}
//PUT: api/Employee/3
[HttpPut("{id}")]
public async Task<IActionResult> PutEmployee(int id, Employee employee){
if(id != employee.Id){
return BadRequest();
}
_context.Entry(employee).State = EntityState.Modified;
try{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException){
if(!EmployeeExists(id)){
return NotFound();
}
else{
throw;
}
}
return NoContent();
}
private bool EmployeeExists(int id)
{
throw new NotImplementedException();
}
//DELETE: api/Employee/3
[HttpDelete("{id}")]
public async Task<ActionResult<Employee>> DeleteEmployee(int id){
var employee = await _context.Thanusiga_Employees.FindAsync(id);
if(employee == null){
return NotFound();
}
_context.Thanusiga_Employees.Remove(employee);
await _context.SaveChangesAsync();
return employee;
}
}
}
Thanks in advance
To upload the image file into database via Asp.net core API, first, we should use IFormFile to send the image file from the client to the API action method. Then, copy the IFormFile to a stream and save it as a byte array in the database.
You could refer the following sample, in this sample, I use two View models to let user enter values and return data to the client.
In Web API, using the following model:
//the view model, used to transfer the user entered value and the image file.
public class FileViewModel
{
public string Name { get; set; }
public IFormFile File { get; set; }
public List<IFormFile> Files { get; set; }
}
//Assume this is your Employee table, and you could also add a property to store the image name.
public class AppFile
{
public int Id { get; set; }
public string Name { get; set; }
public byte[] Content { get; set; } //byte array to store the image data.
}
//this model is used to return the record to client, include the image source, then display the image in the view page.
public class ReturnData
{
public string Name { get; set; }
public string ImageBase64 { get; set; }
}
Upload action method:
[HttpPost]
[Route("upload")]
public async Task<IActionResult> UploadImageProfile([FromForm]FileViewModel fileviewmodel)
{
if (ModelState.IsValid)
{
using (var memoryStream = new MemoryStream())
{
await fileviewmodel.File.CopyToAsync(memoryStream);
// Upload the file if less than 2 MB
if (memoryStream.Length < 2097152)
{
//create a AppFile mdoel and save the image into database.
var file = new AppFile()
{
Name = fileviewmodel.Name,
Content = memoryStream.ToArray()
};
_context.AppFiles.Add(file);
_context.SaveChanges();
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
var returndata = _context.AppFiles
.Where(c => c.Name == fileviewmodel.Name)
.Select(c => new ReturnData()
{
Name = c.Name,
ImageBase64 = String.Format("data:image/png;base64,{0}", Convert.ToBase64String(c.Content))
}).FirstOrDefault();
return Ok(returndata);
}
return Ok("Invalid");
}
Then, in the MVC view page, use the JQuery Ajax to upload the form data and preview the image.
@model WebApplication6.Models.FileViewModel
<div class="row">
<div class="col-md-4">
<form id="myform" enctype="multipart/form-data" asp-action="FileUpload">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<dl>
<dt>
<label asp-for="File"></label>
</dt>
<dd>
<input asp-for="File" type="file">
</dd>
</dl>
</div>
<div class="form-group">
<input type="button" id="btnsubmit" value="Ajax Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div id="imagepreview">
</div>
@section Scripts{
<script>
$(function () {
$("#btnsubmit").click(function () {
var fd = new FormData();
fd.append('name', $("#Name").val())
fd.append('file', $('#File')[0].files[0]);
$.ajax({
url: "/api/todo/upload",
data: fd,
processData: false,
contentType: false,
method: "post",
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (response) {
$("#imagepreview").append("<img src='" + response.imageBase64 + "' alt='' class='img-fluid'>");
}
})
});
});
</script>
}
The result like this:

More detail information about uploading files, see: Upload files in ASP.NET Core.
To Edit the Employee's image, first, you should find the Employee based on the Employee primary key, then, get the Employee information. In the Edit page, you could add a file type element to select a new image, then refer the above code to Edit Employee.
Finally, if you want to delete an Employee, since the image data is in the Employee table, delete the Emploee, it will auto delete the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With