[Simple Way]-ASP.NET Core Upload Multiple File Web API Model


In this post, we are going to create an ASP.NET Core Web API that allows a mobile app client to upload a list of images and save them to the server. Essentially, the client sends multiple files using the ASP.NET Core Web API.

I am developing an ASP.NET Core Web API where users can post images, similar to a gallery. The objective is to store an image along with accompanying text in the database. To accomplish this task, I need to create an API endpoint for the front-end developer. This endpoint should be able to accept multiple images.

  • GalleryModel Class: This class represents a model for handling gallery-related data in the ASP.NET Core application.
  • UserId Property: This property represents the ID of the user associated with the gallery. It's marked with the [Required] attribute, indicating that it must be provided and cannot be null.
  • Images Property: This property represents a collection of image files uploaded to the gallery. It's of type List<IFormFile>, where IFormFile is an interface provided by ASP.NET Core for representing file uploads. This property is also marked with the [Required] attribute, indicating that at least one image must be provided when creating a gallery.

The GalleryModel class provides a structured way to handle data related to gallery creation or updates in the ASP.NET Core application. It ensures that essential data, such as the user ID and uploaded images, are present and valid before processing.

 

Model Class

 public class GalleryModel
    {
        [Required]
public int UserId { get; set; }

        [Required]
public List<IFormFile> Images { get; set; }
    }

So we are going to create an API for Upload Multiple File. 

[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/UpdateGallery
        [HttpPost]
public async Task<IActionResult> UpdateGallery([FromForm] GalleryModel galleryModel)
        {
            Dictionary<string, string> resp = new Dictionary<string, string>();
if (!ModelState.IsValid)
            {
return BadRequest(ModelState);
            }
try
            {
//getting user from the database
if (galleryModel.Images != null)
                {
var path = Path.Combine(_hostingEnvironment.WebRootPath, "galleryimage/");
//checking if "galleryimage" folder exist or not exist then create it
if ((!Directory.Exists(path)))
                    {
                        Directory.CreateDirectory(path);
                    }
foreach (var file in galleryModel.Images)
                    {
//getting file name and combine with path and save it to server folder
string filename = file.FileName;
using (var fileStream = new FileStream(Path.Combine(path, filename), FileMode.Create))
                        {
await file.CopyToAsync(fileStream);
                        }
//here you can write you logic for saving it in the database
                        
                        
                        
                    }
                }

            }
catch (Exception ex)
            {
return BadRequest(ex.Message);
            }
//return api with response
                        resp.Add("status ", "success");
return Ok(resp);
        }
    }


  • Endpoint Setup: The UpdateGallery action method is designated to handle HTTP POST requests targeting the api/User/UpdateGallery endpoint.
  • Method Parameters: The method accepts a single parameter galleryModel, 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. The GalleryModel contains a collection of images to be uploaded.
  • Model Validation: The method checks if the model state is valid. If not, it returns a BadRequest response with the ModelState errors.
  • File Handling: If the Images collection in the galleryModel is not null, the method proceeds to handle each image file. It constructs the file path for storing the images in the galleryimage folder within the web root directory. If the folder doesn't exist, it creates it. Then, it iterates through each image file in the collection, saves it to the server folder, and assigns it a unique filename.
  • Logic: Placeholder comments indicate that logic for saving the images to the database should be implemented at this point. This logic is intended to be added within the foreach loop after saving each image file to the server.
  • Response: Upon successful processing, it returns an OK response with a dictionary containing the success status. If an exception occurs during processing, it returns a BadRequest response with the error message.

This code snippet shows you how to handle the upload of multiple images in an ASP.NET Core Web API endpoint. It saves the images to the server and provides a foundation for implementing logic to save image metadata or other related data to a database.

Let’s Check with postman, open postman and try upload multiple image

Uploading multiple image

you can in the model , we are receiving multiple images.

Getting Multiple image
*Thank you so much if you have a question please comment