1

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/>
2
  • 2
    Because you initialize a new new List<PkgPhotoGallery>(); in each iteration of your foreach loop - you need to initialize it before the loop and add the items inside the loop Commented Mar 26, 2018 at 11:46
  • Thankio. It didn't notice that. Commented Mar 26, 2018 at 12:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.