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.
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);
}
}
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
you can in the model , we are receiving multiple images.
*Thank you so much if you have a question please comment