I create a form where I upload images in database with their individual property. I am using ASP.NET Core MVC and ADO.NET, but now I want to upload multiple images with a single click.
Any idea how to upload multiple images? I want to add all images url into one property then save it into database.
Controller:
public IActionResult aprent([Bind] RentModel ar, [FromForm] string value)
{
try
{
if (ModelState.IsValid)
{
if (ar.imge1 != null)
{
string folder = "image/";
folder += Guid.NewGuid().ToString() + "_" + ar.imge1.FileName ;
ar.pic1 = "/" + folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge1.CopyTo(new FileStream(serverFolder, FileMode.Create));
}
if (ar.imge2 != null)
{
string folder = "image/";
folder += Guid.NewGuid().ToString() + "_" + ar.imge2.FileName;
ar.pic2 = "/" + folder;
string serverFolder = Path.Combine(_IWebHostEnvironment.WebRootPath, folder);
ar.imge2.CopyTo(new FileStream(serverFolder, FileMode.Create));
}
string res = DB.Saverecord(ar);
string pics = DB.imagedb(ar);
TempData["msg"] = res;
}
}
catch (Exception ex)
{
TempData["msg"] = ex.Message;
}
return View();
}
Model:
public IFormFile imge1 { get; set; }
public string? pic2 { get; set; }
public IFormFile? imge2 { get; set; }
Class in which SQL queries are contained:
public string imagedb(RentModel img)
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO img (pic1, pic2, pic3, pic4, pic5 /*,pic6, pic7, pic8, pic9, pic10*/) VALUES (@pic1, @pic2, @pic3, @pic4, @pic5 /*@pic6, @pic7, @pic8, @pic9, @pic10*/)", con);
cmd.Parameters.AddWithValue("@pic1", img.pic1);
cmd.Parameters.AddWithValue("@pic2", img.pic2);
cmd.ExecuteNonQuery();
con.Close();
return "ok";
}
catch (Exception ex)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
return ex.Message.ToString();
}
}