Today, we'll explore how to upload files with .NET Core Web API. We'll develop a straightforward ASP.NET Core Web API that can handle a model along with an image file.
I'm currently engaged in an ASP.NET Core Web API project where we must receive images using form data. Specifically, our application's developer aims to upload images from a React Native app.
To meet this requirement, we'll create a POST API capable of accepting both images using multipart form data.
If you're new to .NET Core, there's no need to worry. By the end of this article, you'll have the knowledge to upload, edit, and delete images using .NET Core Web API. We'll guide you through each step, ensuring a comprehensive understanding.
I have a user table in our database, as shown in the image below. We are using Entity Framework to communicate with the database. When uploading a user profile, if I delete a user, the user profile should also be deleted.
Step 1: Create an Asp core web API project.
Step 1:Create a Model class UserDataModel.cs
for posting data to the controller.
public class UserDataModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string About { get; set; }
[Required]
public IFormFile ProfileImage { get; set; }
}
Step:3 Write logic for accepting images from the post data and deleting a user profile
[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly DbContext _context;
private IHostingEnvironment _hostingEnvironment;
public UserController(DbContext context, IHostingEnvironment environment)
{
_context = context;
_hostingEnvironment = environment ?? throw new ArgumentNullException(nameof(environment));
}
// Post: api/User/UpdateUserData
[HttpPost]
public async Task<IActionResult> UpdateUserData([FromForm] UserDataModel userData)
{
Dictionary<string, string> resp = new Dictionary<string, string>();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
//getting user from the database
var userobj = await _context.TblUser.FindAsync(userData.Id);
if (userobj != null)
{
//Get the complete folder path for storing the profile image inside it.
var path = Path.Combine(_hostingEnvironment.WebRootPath, "images/");
//checking if "images" folder exist or not exist then create it
if ((!Directory.Exists(path)))
{
Directory.CreateDirectory(path);
}
//getting file name and combine with path and save it
string filename = userData.ProfileImage.FileName;
using (var fileStream = new FileStream(Path.Combine(path, filename), FileMode.Create))
{
await userData.ProfileImage.CopyToAsync(fileStream);
}
//save folder path
userobj.ProfilePicture = "images/" + filename;
userobj.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
//return api with response
resp.Add("status ", "success");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(resp);
}
}
Above code snippet demonstrates how to handle multipart form data file uploads in an ASP.NET Core Web API, specifically for updating user profiles with an image upload feature.
Lets do testing with postman
you can check the uploaded image in your wwwroot=>images folder, if you do not have a wwwroot folder then manually create the wwwroot folder in your asp core API project.
For deleting image file asp core when we delete user from the database , create a delete api , you can see in the below code.
// Post: api/User/Delete
[HttpDelete]
public async Task<IActionResult> Delete(int id)
{
Dictionary<string, string> resp = new Dictionary<string, string>();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
//getting user from the database
var userobj = await _context.TblUser.FindAsync(id);
if (userobj != null)
{
//Get the complete folder path for storing the profile image inside it.
var path = Path.Combine(_hostingEnvironment.WebRootPath, userobj.ProfilePicture);
//checking if "image" exist then delete it
if ((!Directory.Exists(path)))
{
System.IO.File.Delete(path);
}
_context.TblUser.Remove(userobj);
await _context.SaveChangesAsync();
//return api with response
resp.Add("status ", "deleted successfully");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(resp);
}
*Thank you so much if you have a question please comment
Above code shows how to handle user deletion in an ASP.NET Core Web API, including the deletion of associated profile images from the server.
IFormFile
ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request.
ASP.NET Core has introduced IFormFile To upload files in ASP.NET Core. IFormFile provides us access to information of files for example FileName ,Header,ContentDisposition , ContentType, FileName etc.
This interface also allows us to read the contents of an uploaded file, and if you using asp core MVC with the view then the name of the IFormFile parameter and the name of the HTML FileUpload input element must be the same, otherwise, you will not get the file in the IFormFile.