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.

Tbluser

Image Uploading in Dot net core Web API

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);
        }
    }


  • UpdateUserData Action: This action method is decorated with the [HttpPost] attribute, indicating that it handles HTTP POST requests. It's responsible for updating user data with the provided model.
  • Method Parameters: The UpdateUserData method accepts a single parameter userData, which is annotated with the [FromForm] attribute. This indicates that the data for this parameter will be retrieved from the form data of the HTTP request.
  • Model Validation: The method checks if the model state is valid. If not, it returns a BadRequest response with the ModelState errors.
  • User Retrieval: It retrieves the user from the database using the provided Id from the userData.
  • File Handling: The method handles the uploaded profile image file. It constructs the file path for storing the image in the webroot's images directory. If the directory doesn't exist, it creates it. Then, it saves the uploaded image file to the specified path.
  • Update User Profile: It updates the user's profile picture path and the UpdatedAt property with the current timestamp.
  • Response: If the operation is successful, it returns an OK response with a dictionary containing the success status. If an exception occurs, it returns a BadRequest response with the error message.

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.

Upload Image in asp core

Capture image file

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

  • Delete Action: This action method is decorated with the [HttpDelete] attribute, indicating that it handles HTTP DELETE requests. It's responsible for deleting a user with the provided id.
  • Method Parameters: The Delete method accepts a single parameter id, which represents the identifier of the user to be deleted.
  • User Retrieval: It retrieves the user from the database using the provided id.
  • File Handling: It constructs the file path for the user's profile image. If the image file exists, it deletes it from the server.
  • User Deletion: The user object is removed from the database using _context.TblUser.Remove(userobj). The changes are then saved to the database using _context.SaveChangesAsync().
  • Response: If the operation is successful, it returns an OK response with a dictionary containing the success status. If an exception occurs, it returns a BadRequest response with the error message.

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.