I am trying to upload multiple images and then store them in database.
The problem is all the images are being saved in the images folder. But in the database, the name of the last image uploaded is being shown.
For example if i uploaded 3 images 1 2 and 3. all the three images will be saved in the folder but the name of only last image is uploaded is shown in database.
Following is the code of Controller:
public ActionResult Create(IEnumerable<HttpPostedFileBase> files)
{
foreach (var filed in files)
{
if (filed != null && filed.ContentLength > 0)
{
var gphoto = new PkgPhotoGallery
{
FileName = Guid.NewGuid().ToString() + Path.GetExtension(filed.FileName),
FileType = FileType.Image
};
filed.SaveAs(Path.Combine(Server.MapPath("~/PackagePhotoGallery"), gphoto.FileName));
packages.PkgPhotoGalleries = new List<PkgPhotoGallery>();
packages.PkgPhotoGalleries.Add(gphoto);
}
}
db.Packages.Add(packages);
db.SaveChanges();
return RedirectToAction("Index");
}
Follwoing is the code of Model
public class PkgPhotoGallery
{
[Key]
public int FileId { get; set; }
public string FileName { get; set; }
public FileType FileType { get; set; }
public int? PackageId { get; set; }
public virtual Packages Packages { get; set; }
}
Code of View
<input type="file" name="files" multiple/>