Image Upload in NET Core Web API

[Simple Way]- Image Upload in .NET Core Web API

Today we will learn How to upload a file with .NET CORE Web API Web API. We will create a simple ASP core web API that accepts the model with an image file.

Recently, I’m working on an ASP CORE web API project, in which we need to receive the image using form data. Basically, my App app developer wants to upload the image from the React Native App. 

That’s why we create a POST API that accepts both images using multipart.

If you are new to dot net core then don’t worry. after reading this article you can upload, edit and delete an image using dot net core WEB API. we will show you all step by step. 

I have a user table in our database as you can see below image and we are using the entity framework for communicating with the database. we will upload a user profile if I delete a user, the user profile also should 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);
        }
    }

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

 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.

 

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Your Header Sidebar area is currently empty. Hurry up and add some widgets.